public class Example{
public static void main(String args[]){
A target=new A(); //线程thread的目标对象
Thread thread=new Thread(target);
thread.setName("张三");
thread.start();
while(target.getStop()==false){}
System.out.println("我是主线程,负责恢复"+thread.getName()+"线程");
target.restart(); //恢复thread线程
}
}
class A implements Runnable{
int number=0;
boolean stop=false;
boolean getStop(){
return stop;
}
public void run(){
while(true){
number++;
System.out.println(Thread.currentThread().getName()+"的number="+number);
if(number==3){
try{ System.out.println(Thread.currentThread().getName()+"被挂起");
stop=true;
hangUP();//挂起线程
System.out.println(Thread.currentThread().getName()+"恢复执行");
}
catch(Exception e){}
}
try{ Thread.sleep(1000);
}
catch(Exception e){}
}
}
public synchronized void hangUP() throws InterruptedException{
wait();
}
public synchronized void restart(){
notifyAll();
}
}求教,main方法中的空循环是做什么用的?初学线程,不是很理解。
解决方案 »
- 一个关于代码设计模式的问题
- pps.put("file.encoding", "ISO-8859-1")配置无效问题
- com.sun.management包的疑问?
- 实现逆矩阵的算法!
- 搞不定了! HttpClient 中文乱码!
- j2sdk 1.4.2跟j2sdk1.4.2_04有啥区别
- 可否解释为何出现这样的结果
- 线程间通信测试,使用sleep()问题?为什么永远只能打出“Rose---->male",打不出“Rose--->female"
- 在线等!!!!!!
- jPopupMenu为什么在Canvas中只能在边缘显示,而在JPanel中显示没问题
- .class 文件 反编译后如何编译
- String作为引用类型到底特殊在哪儿?
子线程就不运行又是怎么回事?难道是抢不到CPU控制权?
如果这种情况抢不到,那么空循环为什么又能抢到呢?
等待target线程结束,target线程运行在主线程main里面,如果没有这个空循环,主线程顺序执行,target还没有执行完得时候主线程已经执行完退出了,会导致target也退出。