写了一个卖票的例子用synchronized结果每次是一个线程的名字在输出,虽然线程有随机性,但也不会每次都抢到吧。。。这是为什么呀
public class MyRunnable implements Runnable {
private int ticket = 100;
private Object object = new Object();
public void run() {
while (true) {
synchronized (object) {
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":出售第" + (101 - ticket) + "张票");
ticket -= 1;
}
}
}
}
}
//主函数
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread t1 = new Thread(myRunnable,"窗口1");
Thread t2 = new Thread(myRunnable,"窗口2");
Thread t3 = new Thread(myRunnable,"窗口3");
t1.start();
t2.start();
t3.start();
}
}