还是一个的线程问题
代码如下:(问题在运行结果那里)-----------------------------------------------------------------------------------------------------------------------------------
class MyThread implements Runnable {
private int ticket = 5;
public void run() {
for (int i = 0; i < 5; ++i) {
//synchronized (this) {
if (ticket > 0) {
try {
//Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "卖票: ticket = " + (ticket--));
}
//}
}
}
}
public class Test2 {
public static void main(String[] agrs) {
MyThread mt = new MyThread();
Thread t1 = new Thread(mt);
Thread t2 = new Thread(mt);
Thread t3 = new Thread(mt);
t1.start();
t2.start();
t3.start();
}
}
一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一
运行结果却是:
------------------------------------------------------------------------------------------------------------------------------------------
Thread-1卖票: ticket = 3
Thread-2卖票: ticket = 5 //怎么5会在3的下面?
Thread-0卖票: ticket = 4
Thread-0卖票: ticket = 2
Thread-1卖票: ticket = 2
Thread-2卖票: ticket = 2
Thread-2卖票: ticket = 1
Thread-1卖票: ticket = 1
Thread-0卖票: ticket = 0