todo:有空测试一下线程池的shutdown方法看能否成功
Runable
package sample;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class testRunnable1 implements Runnable {
boolean mark = false;
@Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yymmdd");
int count = 0;
System.out.println("Thread start:" + sdf.format(new Date()));
for (int i = 0; i < 1000; i++) {
if (mark) {
Thread.currentThread().getThreadGroup().interrupt();
for (int is = 0; is < 10; i++) {
Thread.currentThread().getThreadGroup().interrupt();
}
break;
}
count++;
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + ":" + count + "");
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println(Thread.currentThread().getThreadGroup().getName() + ":" + Thread.currentThread().getName() + "被终止");
}
}
System.out.println("Thread end :" + sdf.format(new Date()));
}
}
调用
package sample;
import java.io.IOException;
class propertyT{
static volatile boolean flag = true;
public static void main(String[] args) throws InterruptedException, IOException {
// Utils.write("r3","22");
// Utils.write("r5","55");
ThreadGroup tg1 = new ThreadGroup("我是一个新的线程组1");
ThreadGroup tg2 = new ThreadGroup("我是一个新的线程组2");
testRunnable1 tr1 = new testRunnable1();
new Thread(tg1,tr1,"tr1").start();
testRunnable1 tr2 = new testRunnable1();
new Thread(tg1,tr2,"tr2").start();
testRunnable1 tr = new testRunnable1();
new Thread(tg2,tr,"tr").start();
testRunnable1 tr3 = new testRunnable1();
new Thread(tg2,tr3,"tr3").start();
testRunnable1 tr4 = new testRunnable1();
new Thread(tg2,tr4,"tr4").start();
Thread.sleep(5000);
//给tg2线程组停止所有线程
tr.mark = true;
}
}
重点代码
Thread.currentThread().getThreadGroup().interrupt()
需要多调用几次
for (int is = 0; is < 10; i++) {
Thread.currentThread().getThreadGroup().interrupt();
}