java 线程池 优雅停止

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
* @author 201409150096
*
*/
public class ThreadTestCase extends Thread {

private boolean status;
private ArrayBlockingQueue<String> q;
private Object lock;

public ThreadTestCase(ArrayBlockingQueue<String> q) {
this.status = true;
lock = new Object();
this.q = q;
}

public void shutdown() {
synchronized (lock) {
this.status = false;
System.out.println("TT-shutdown()-call");
}
}

public void interrupt() {
System.out.println("TT-interrupt()-call");
super.interrupt();
}

public void run() {
int j = 0;
while ((!this.currentThread().isInterrupted()) && status) {
try {
int sum = 0;
// System.out.println(Thread.currentThread().getThreadGroup()
// + "----" + Thread.currentThread().getName());
// try {
// j=11;
q.take();
for (int i = 0; i < 1000000; i++) {
sum++;
}
System.out.println(Thread.currentThread().getName() + "|" + sum
+ "|" + this.currentThread().isInterrupted());
// int i = -1;
// while (i > 0) {
// this.sleep(1);
// }
} catch (InterruptedException e) {
this.shutdown();
// e.printStackTrace();
System.out.println("InterruptedException");
}
// } catch (IllegalMonitorStateException e) {
// this.shutdown();
// e.printStackTrace();
// System.out.println("IllegalMonitorStateException");
// }
}
}

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("start");
ArrayBlockingQueue<String> q = new ArrayBlockingQueue<String>(100);
for (int i = 0; i < 100; i++) {
try {
q.put(i + "");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
List<ThreadTestCase> threadList = new ArrayList<ThreadTestCase>();

// for (int i = 0; i < 10; i++) {
// TT t = new TT();
// threadList.add(t);
// t.start();
// }
ThreadPoolExecutor ex = (ThreadPoolExecutor) Executors
.newFixedThreadPool(10);
for (int i = 0; i < 3; i++) {
ThreadTestCase t = new ThreadTestCase(q);
threadList.add(t);
ex.execute(t);
}

while (ex.getPoolSize() < 3) {
System.out.println("main-sleep");
}
// for (int i = 0; i < threadList.size(); i++) {
// Thread t = threadList.get(i);
// try {
// t.join();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// }
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}

for (int i = 0; i < threadList.size(); i++) {
ThreadTestCase t = threadList.get(i);
// t.interrupt();
// t.shutdown();
}
// ex.shutdown();
// ex.join();\
int t = 5;
while (t-- > 0) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// ex.shutdown();
System.out.println("ex.shutdownNow" + ex.shutdownNow());
}

System.out.println("end" + q.size());
}
}

猜你喜欢

转载自foxox.iteye.com/blog/2166078