java 多线程问题

heiyee 2012-06-30 10:08:31
package yang.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Exercise22 {

public static void main(String[] args) {
Thread coop1 = new Thread(new Coop1());
coop1.start();
Thread coop2 = new Thread(new Coop2(coop1));
coop2.start();

// Runnable coop1 = new Coop1(),
// coop2 = new Coop2(coop1);
// ExecutorService exec = Executors.newCachedThreadPool();
// exec.execute(coop1);
// exec.execute(coop2);
// Thread.yield();
// exec.shutdown();

}
}

class Coop1 implements Runnable {
public Coop1(){
System.out.println("Coop1 constructed!");
}
@Override
public void run() {
System.out.println("Coop1 going into wait...");
synchronized(this){
try{
wait();
}catch(InterruptedException e){
System.out.println("Stoped by InterruptedException.");
}
System.out.println("Coop1 is running to the exit.");
}
}
}

class Coop2 implements Runnable {
Runnable otherTask;
public Coop2(Runnable otherTask){
this.otherTask = otherTask;
System.out.println("Coop2 constructed.");
}
@Override
public void run() {
System.out.println("Coop2 pause 5 seconds.");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Notify other task now...");
synchronized(otherTask){
otherTask.notifyAll();
}
}
}


当我注释之后Coop1的线程就无法执行完毕,注释start方法启用线程,改用execute之后却好好的,这是为什么?这两种方式有什么区别?请高手指点!
...全文
152 3 打赏 收藏 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
sffx123 2012-07-03
  • 打赏
  • 举报
回复
楼上说的很好了,这样改一下就行了

Runnable c1 = new Coop1();
Thread coop1 = new Thread(c1);
coop1.start();
Thread coop2 = new Thread(new Coop2(c1));
coop2.start();
锁的不是同一个对象
风火轮 2012-06-30
  • 打赏
  • 举报
回复
Runnable coop1 = new Coop1(),
// coop2 = new Coop2(coop1);
// ExecutorService exec = Executors.newCachedThreadPool();
// exec.execute(coop1);
// exec.execute(coop2);
// Thread.yield();
// exec.shutdown();


共用 同一个对象 coop1 当然可以唤醒

前面 一个等待是 new Coop1()对象 唤醒的是new Thread(new Coop1())对象 不是同一个唤醒不了
风火轮 2012-06-30
  • 打赏
  • 举报
回复
Thread coop1 = new Thread(new Coop1()); 传得是new Coop1() 对象 他被wait() 没人唤醒他
coop1.start();
Thread coop2 = new Thread(new Coop2(coop1)); 你的otherTask.notifyAll(); 的对象锁otherTask 和前面new Coop1() 不是同一个 唤醒不了前面的等待



62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧