62,620
社区成员
发帖
与我相关
我的任务
分享public class ThreadTest_2 extends Thread {
private boolean isDeath;
private int count;
private boolean finish;
public void run() {
try {
// 任务开始时先停一指定时间
// 目的是让外部的join()方法有时间执行
Thread.sleep(1000);
while (!isDeath) {
// Thread.sleep(1000);
// some statements .... 运行相关任务
System.out.println("start working ... " + this.getName());
// 模拟僵死A 没有机会抛InterruptedException 根本无法中断线程
while (true) {
Thread.sleep(10);
if (count == 2) {
break;
}
}
// 模拟僵死A 没有机会抛InterruptedException 根本无法中断线程
// 任务周期计数
count++;
// 任务完成
finish = true;
Thread.sleep(1000);
// 这里为了测试设置任务只执行一次
break;
}
} catch (InterruptedException e) {
System.out.println("I'm interrupted ! OK The Thread "
+ this.getName() + " is over !");
}
}
public boolean isFinish(){
return finish;
}
public void terminate(){
isDeath = false;
}
}public class Test_2 {
public static void main(String[] args) {
System.out.println("初始化... ");
System.out.println("开始测试 ...");
// 开始任务
ThreadTest_2 s1 = new ThreadTest_2();
ThreadTest_2 s2 = new ThreadTest_2();
s1.start();
s2.start();
try {
s1.join(2000);
s2.join(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
if (!s1.isFinish()) {
System.out.println("s1 is alive : " + s1.isAlive());
s1.interrupt();
Thread.sleep(500);
System.out.println("s1 is alive : " + s1.isAlive());
System.out.println("s1 Thread " + s1.getName() + " ? ");
// s1.stop();
System.out.println("s1 is over!");
}
if (!s2.isFinish()) {
System.out.println("s2 is alive : " + s2.isAlive());
s2.interrupt();
Thread.sleep(500);
System.out.println("s2 is alive : " + s2.isAlive());
System.out.println("s2 Thread " + s2.getName() + " ? ");
// s2.stop();
System.out.println("s2 is over!");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
// System.exit(0) ;
}
} public void run() {
try {
// 任务开始时先停一指定时间
// 目的是让外部的join()方法有时间执行
Thread.sleep(1000);
while (!isDeath) {
// Thread.sleep(1000);
// some statements .... 运行相关任务
System.out.println("start working ... " + this.getName());
// 模拟僵死A 没有机会抛InterruptedException 根本无法中断线程
while (true) {
Thread.sleep(10);
if (count == 2) {
break;
}
}
// 模拟僵死A 没有机会抛InterruptedException 根本无法中断线程
// 任务周期计数
count++;
// 任务完成
finish = true;
Thread.sleep(1000);
// 这里为了测试设置任务只执行一次
break;
}
} catch (InterruptedException e) {
System.out.println("I'm interrupted ! OK The Thread "
+ this.getName() + " is over !");
}