public class UnsafeThread implements Runnable {
private int tickets=50;
Object obj=new Object();
public void run() {
while(true)
{
synchronized(obj){ //这个地方this与obj 有何区别。
if(tickets>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":"+tickets--);
}
}
}
}
public static void main(String[] args) {
UnsafeThread unSafe=new UnsafeThread();
Thread thread1=new Thread(unSafe);
Thread thread2=new Thread(unSafe);
thread1.start();
thread2.start();
}
} |