- synchronized:同步(锁),可以修饰代码块和方法,被修饰的代码块和方法一旦被某个线程访问,则直接锁住,其他的线程将无法访问
- 非静态方法的同步锁对象是this
静态方法的锁同步对象是当前类的字节码对象
模拟火车站售票案例
同步代码块:
public class Ticket implements Runnable {
int tickets = 100;//总票数
Object obj = new Object(); //锁对象
@Override
public void run() {
//卖票
while (true) {
synchronized (obj) {
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "卖出了第" + (tickets--) + "张票");
}
}
}
}
}
同步方法
public class Ticket implements Runnable {
int tickets = 100;//总票数
Object obj = new Object(); //锁对象
@Override
public void run() {
//卖票
while (true) {
method();
}
}
public synchronized void method(){
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "卖出了第" + (tickets--) + "张票");
}
}
}
测试类
public class TicketTest {
public static void main(String args[]){
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/191874.html