62,635
社区成员




public class TestThread {
private Thread thread1;
public static void main(String[] args) {
TestThread t = new TestThread();
t.createTread1();
}
/*
* 启动线程
*/
public void createTread1(){
thread1 = new Thread(new ThreadI());
thread1.start();
}
/*
* 判断线程是否死亡,重启线程
*/
public void resetThread1(){
System.out.println("是否存活: "+thread1.isAlive());
if(!thread1.isAlive())
{
createTread1();
}
}
/*
* 伺服线程
*/
class ThreadI implements Runnable {
private int temp = 0;
public void run() {
try{
while (true) {
try {
if(temp>=10)
throw new RuntimeException();
System.out.println("------------循环显示中---------");
Thread.sleep(2000);
temp++;
} catch (Exception e) {
break;
}
}
}finally{
System.out.println("后判断 是否存活");
//try {
// Thread.currentThread().join();
//} catch (InterruptedException e) {
// e.printStackTrace();
//}
resetThread1();
}
}
}
}
private Thread thread1;
public static void main(String[] args) {
TestThread t = new TestThread();
t.createTread1();
}
/*
* 启动线程
*/
public void createTread1(){
thread1 = new Thread(new ThreadI());
thread1.start();
}
/*
* 判断线程是否死亡,重启线程
*/
public void resetThread1(){
thread1=null;
createTread1();
}
/*
* 伺服线程
*/
class ThreadI implements Runnable {
private int temp = 0;
public void run() {
try{
while (true) {
try {
if(temp>=10)
throw new RuntimeException();
System.out.println("------------循环显示中---------");
Thread.sleep(2000);
temp++;
} catch (Exception e) {
break;
}
}
}finally{
System.out.println("后判断 是否存活");
resetThread1();
}
}
}
}
public class TestThread {
private Thread thread1;
boolean flag = false;//加个标志位
public static void main(String[] args) {
TestThread t = new TestThread();
t.createTread1();
}
/*
* 启动线程
*/
public void createTread1(){
thread1 = new Thread(new ThreadI());
thread1.start();
}
/*
* 判断线程是否死亡,重启线程
*/
public void resetThread1(){
System.out.println("是否存活: "+thread1.isAlive());
if(flag) //用标志位判断
{
createTread1();
falg = false; //创建好后再置回false;以便下次再用
}
}
/*
* 伺服线程
*/
class ThreadI implements Runnable {
private int temp = 0;
public void run() {
try{
while (true) {
try {
if(temp>=10)
throw new RuntimeException();
System.out.println("------------循环显示中---------");
Thread.sleep(2000);
temp++;
} catch (Exception e) {
break;
}
}
}finally{
System.out.println("后判断 是否存活");
flag = true;// 结束之前把标志位置true
//try {
// Thread.currentThread().join();
//} catch (InterruptedException e) {
// e.printStackTrace();
//}
resetThread1();
}
}
}
}