Executors.newSingleThreadExecutor()返回一个线程池(这个线程池只有一个线程)
,这个线程池可以在线程死后(或发生异常时)重新启动一个线程来替代原来的线程继续执行下去!
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Yao implements Runnable {
public String name ;
public Yao(String name){
this.name = name;
}
public static void foo(Yao d) {
d = new Yao("Fifi");
}
public static void main(String[] args) {
Yao yao = new Yao("Max");
foo(yao);
System.out.println(" aDog.name.equals Max = "+ yao.name.equals("Max"));
ExecutorService eService = Executors.newSingleThreadExecutor();
eService.execute(yao);
}
@Override
public void run() {
int temp = 0;
int i = 0;
Random random =new Random();
while(true){
int j =random .nextInt(100);
System.err.println("temp----------->"+temp+" i---------------->"+(i++)+" j------------------>"+j);
try{
if(temp==0&&j>90) temp = 7/0;
Thread.currentThread().sleep(10);
}catch(Exception e){
e.printStackTrace();
temp = 1;
}
}
}
}
执行的结果如下(注意temp的值的变化和异常输出):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|