程序:
class Test{
public static void main(String[] args){
TestThread t = new TestThread();
new Thread(t).start();
try{Thread.sleep(1000);}catch(Exception e){}
t.str = new String("method");
new Thread(t).start();
System.out.println(Thread.currentThread().getName()
+ " is running");
}
}
class TestThread implements Runnable{
private int tickets = 20;
String str = new String("");
public void run(){
if(str.equals("method")){
while(true){
sale();
}
}
else{
synchronized(str){
if(tickets > 0){
try{
Thread.sleep(10);
}
catch(Exception e){
System.out.println(e.getMessage());
}
System.out.println("synchronized(str) is running");
System.out.println(Thread.currentThread().getName()
+" is salling ticket " + tickets--);
}
}
}
}
public synchronized void sale(){
if(tickets > 0){
try{
Thread.sleep(10);
}
catch(Exception e){
System.out.println(e.getMessage());
}
System.out.println("method");
System.out.println(Thread.currentThread().getName()
+ " is salling ticket " + tickets--);
}
}
}
输出:
synchronized(str) is running
Thread-0 is salling ticket 20
main is running
method
Thread-1 is salling ticket 19
method
Thread-1 is salling ticket 18
method
Thread-1 is salling ticket 17
method
Thread-1 is salling ticket 16
method
Thread-1 is salling ticket 15
method
Thread-1 is salling ticket 14
method
Thread-1 is salling ticket 13
method
Thread-1 is salling ticket 12
method
Thread-1 is salling ticket 11
method
Thread-1 is salling ticket 10
method
Thread-1 is salling ticket 9
method
Thread-1 is salling ticket 8
method
Thread-1 is salling ticket 7
method
Thread-1 is salling ticket 6
method
Thread-1 is salling ticket 5
method
Thread-1 is salling ticket 4
method
Thread-1 is salling ticket 3
method
Thread-1 is salling ticket 2
method
Thread-1 is salling ticket 1
问:
1.Thread.sleep休眠的是当前的线程,在上面程序中休眠的就是主线程main,
同时导致了线程Thread-1休眠期不能开启,这里的分析正确?
2.如果上面正解的话,try{Thread.sleep(1000);}catch(Exception e){}
这句代码为什么不能保证tickets在线程Thread-0中被完全售出?
------最佳解决方案--------------------------------------------------------
1.Thread.sleep休眠的是当前的线程,在上面程序中休眠的就是主线程main,
同时导致了线程Thread-1休眠期不能开启,这里的分析正确?
——正确
2.如果上面正解的话,try{Thread.sleep(1000);}catch(Exception e){}
这句代码为什么不能保证tickets在线程Thread-0中被完全售出?
——你的代码逻辑就是这么控制的啊!
public void run(){
if (str.equals("method")){ // Thread-0执行到此时,str还是空字符串,所以if不成立
while(true){sale();} // 循环卖掉所有票
} else{
synchronized(str){
if(tickets > 0){ // 只卖掉一张,if并不循环
....