关于Thread.sleep休眠
程序:
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.你的代码
try{Thread.sleep(1000);}catch(Exception e){}
是写在主线程Main当中的,所以休眠的是主线程。而Thread-1是线程,他是异步执行,不受主线程的影响,按照你定义的
while (true) {
sale();
}
售出。Thread-1不会受到主线程的影响,因为他们是异步的。
2.你的票是已经卖完了为tickets=0,之所以打印出来是1,是因为是你用了tickets--,打印tickets=1时,他就执行tickets--,结果tickets=0,则下一次执行不满足if (tickets > 0) {所以不会执行。
------解决方案--------------------1.Thread.sleep休眠的是当前的线程,在上面程序中休眠的就是主线程main,
同时导致了线程Thread-1休眠期不能开启,这里的分析正确?
——正确
2.如果上面正解的话,try{Thread.sleep(1000);}catch(Exception e){}