程序的目的是:A,B,C三个线程合作按顺序连续打印十次自己的ID。ABC ABC ABC这样下去。
用线程的start方法可以成功,但是使用了ExecutorService缺阻塞了,为什么呢?本人对线程不熟悉,恳请赐教。
package Test;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class TestThreadLocal {
public static void main(String[] args) {
mythread A=new mythread("A");
mythread B=new mythread("B");
mythread C=new mythread("C");
// A.start();//如果直接start程序可以正确运行。
// B.start();
// C.start();
ExecutorService es=Executors.newCachedThreadPool();//这样使用会阻塞的。为什么呢?
es.execute(A);
es.execute(B);
es.execute(C);
es.shutdown();
}}class mythread extends Thread{
public static boolean flag=true;
public static String turn="A";//用来保证线程执行顺序的。
public String name;
public mythread(String name){
super(name);
this.name=name;
}
public synchronized static void print() throws InterruptedException {
String temp=currentThread().getName();
while(!temp.equals(turn)){
mythread.class.wait();
}
System.out.print(temp);
if(temp.equals("A"))turn="B";
if(temp.equals("B"))turn="C";
if(temp.equals("C")){
turn="A";
System.out.println();
}
mythread.class.notifyAll();
}
public void run(){
for(int i = 0;i<10;i++) {
try {
print();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
用线程的start方法可以成功,但是使用了ExecutorService缺阻塞了,为什么呢?本人对线程不熟悉,恳请赐教。
package Test;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class TestThreadLocal {
public static void main(String[] args) {
mythread A=new mythread("A");
mythread B=new mythread("B");
mythread C=new mythread("C");
// A.start();//如果直接start程序可以正确运行。
// B.start();
// C.start();
ExecutorService es=Executors.newCachedThreadPool();//这样使用会阻塞的。为什么呢?
es.execute(A);
es.execute(B);
es.execute(C);
es.shutdown();
}}class mythread extends Thread{
public static boolean flag=true;
public static String turn="A";//用来保证线程执行顺序的。
public String name;
public mythread(String name){
super(name);
this.name=name;
}
public synchronized static void print() throws InterruptedException {
String temp=currentThread().getName();
while(!temp.equals(turn)){
mythread.class.wait();
}
System.out.print(temp);
if(temp.equals("A"))turn="B";
if(temp.equals("B"))turn="C";
if(temp.equals("C")){
turn="A";
System.out.println();
}
mythread.class.notifyAll();
}
public void run(){
for(int i = 0;i<10;i++) {
try {
print();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货