对休眠Thread.sleep(500);有疑问
当运行多线程时,程序运行到Thread.sleep(500);会不会换到下一个线程?
package 多线程currentThread;
public class Road implements Runnable {
Thread attachThread;
public void setAttachThread(Thread t){
attachThread=t;
}
@Override
public void run() {
// TODO Auto-generated method stub
String name=Thread.currentThread().getName();
if(name.equals("司机")){
try{
System.out.println("我是"+name+"在马路上开车");
System.out.println("想睡上一个小时后开车");
Thread.sleep(1000*60*60);
}
catch(InterruptedException e){
System.out.println(name+"被警察叫醒了");
}
System.out.println(name+"继续开车");
}
else if(name.equals("警察")){
for(int i=1;i<=3;i++){
System.out.println(name+"喊:开车");
try{
Thread.sleep(500);
}
catch(InterruptedException e){}
}
attachThread.interrupt();
}
}
}
[解决办法]
sleep意味着阻塞了,此时CPU不会分配时间片给该线程,会执行别的线程。
[解决办法]
是的,500毫秒后就给其他线程了