新手问个简单的问题:
为什么以下代码运行结果是这样的呢?
Thread-0出售票20
Thread-0出售票19
Thread-0出售票18
Thread-0出售票17
Thread-0出售票16
Thread-0出售票15
Thread-0出售票14
Thread-0出售票13
Thread-0出售票12
Thread-0出售票11
Thread-0出售票10
Thread-0出售票9
Thread-0出售票8
Thread-0出售票7
Thread-0出售票6
Thread-0出售票5
Thread-0出售票4
Thread-0出售票3
Thread-0出售票2
Thread-0出售票1
public class ThreadDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestThread t = new TestThread();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
class TestThread implements Runnable {
private int tickets = 20;
public void run() {
while(true) {
if(tickets>0)
System.out.println(Thread.currentThread().getName()+"出售票"+tickets--);
}
}
}
This should not happen if you run it a few more times. If you change system.out to write to a file, it will definitely output multi-threaded output.
It should be related to the thread scheduling of the virtual machine. If the second thread has not started before the completion of 20 cycles, of course only thread-0 will run. If the subsequent thread starts before the end of 20 runs, it will There will be multiple threads outputting. If you try changing to 2000, there will definitely be a lot of threads outputting.