/*
需求 同步代码块
同步锁
*/
class Ticket implements Runnable{
private int num;
Object obj = new Object();
Ticket(int num){
this.num = num;
}
//重写run方法
public void run(){
while(true){
synchronizzed(obj){
System.out.println(Thread.current().getName());
}
}
}
}
class TicketLock{
public static void main(String[] args){
//创建Runnable子类对象
Ticket t = new Ticket(150);
//创建Thread子类对象(创建线程),并传入接口子类对象,
Thread th1 = new Thread(t);
Thread th2 = new Thread(t);
Thread th3 = new Thread(t);
Thread th4 = new Thread(t);
//调用start()方法,开启Run方法
th1.start();
th2.start();
th3.start();
th4.start();
}
} |
|