public class ThreadTest extends Thread { public void run() {
while(true){
System.out.println(this.getName());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} public static void main(String[] args) throws Exception {
ThreadTest t = new ThreadTest();
t.start();
t.wait();//这样是错的
}
}能否在main线程中调用其他线程的wait(),使之等待
是否wait()只能由自身线程调用?那想要调用wait()来实现使其他线程等待,那要如何实现呢?(不在while()中用标示)
解决方案 »
- swing 点击Jbutton后 弹出一个网页 如何做?
- 请教 newInstance()
- JSP 拒绝编译 POI 类!为什么会有 Java Application 可以编译、而 JSP 却拒绝进行编译的类?
- 急需JAVA人才,有意请于我联系!
- 关于接口调用的问题
- 如何double类型的数值,输出成#,###.##格式
- 菜鸟提问:何谓“群集”、“容器”和“迭代”?
- 关于note:configDgj.java uses or overrides a deprecated Api的问题?
- 怎么把.class文件转变成.java文件?用什么命令?
- Happy Thanksgiving Day!
- 长春径点科技(avepoint)部分面试题(含答案)
- 笔试题
wait一个要在同步方法或者同步块里面synchronized
顺便引一篇相关的老帖,看5楼的回答。
http://topic.csdn.net/t/20030902/02/2213119.html
可以sleep()
public class ThreadTest extends Thread { public void run() {
while(true){
System.out.println(this.getName());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void pause(){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public static void main(String[] args) throws InterruptedException {
ThreadTest t = new ThreadTest();
t.start();
t.pause();
}
}
public class ThreadTest extends Thread { public void run() {
while(true){
System.out.println(this.getName());
this.pause();
}
}
public synchronized void pause(){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public static void main(String[] args) throws InterruptedException {
ThreadTest t = new ThreadTest();
t.start();
t.pause();
}
}
wait()只能作用在执行这个方法的线程上,而非这个方法属于的那个线程?
看api文档:
wait()
Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.wait()方法只能让当前线程阻塞,你在在A线程中调用B线程的wait()方法,结果还是A线程阻塞。
在A线程中调用任何对象的wait()都是使A线程阻塞
B线程要阻塞,为什么要用A线程来掉呢?完全可以B线程自己调用wait嘛。