java多线程小问题
各位大大,以下这段程序,在if语句中,“让线程先打印再sleep”和“让线程先sleep再打印”,结果为什么会不同?如果先sleep的话,只有一个线程在跑,why why why。。。急问
class Sell implements Runnable {
int ticket = 50;
String str = "";
public void run() {
while(true) {
synchronized(str) {
if(ticket > 0) {
try {Thread.sleep(100);} catch(Exception e) {}
System.out.println(Thread.currentThread().getName() + " is selling ticket " + ticket--);
//try {Thread.sleep(100);} catch(Exception e) {}
}
}
}
}
}
class TestSell {
public static void main(String args[]) {
Sell s1 = new Sell();
new Thread(s1).start();
new Thread(s1).start();
new Thread(s1).start();
new Thread(s1).start();
}
}