我想 实现一个多窗口卖票的目的,在该背景下探究多线程的线程安全问题
想要达成的效果是,三个线程抢占cpu执行权
结果代码执行出来三个线程是依次执行的,没有很懂其中的原因
public class WindowTest1 {
public static void main(String[] args) {
Window1 w1 = new Window1();
Thread t = new Thread(w1);
Window1 w2 = new Window1();
Thread t1 = new Thread(w2);
Window1 w3 = new Window1();
Thread t2 = new Thread(w3);
t.start();
t1.start();
t2.start();
}
}
class Window1 implements Runnable{
private int ticket = 100;
@Override
public void run() {
while (true){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(ticket > 0){
System.out.println(Thread.currentThread().getName()+":卖票,票号为:"+ticket);
ticket--;
}else{
break;
}
}
}
}