java 多线程问题
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之后却好好的,这是为什么?这两种方式有什么区别?请高手指点!