Two-Phase Termination Pattern
Two-Phase Termination Pattern很简单,但该模式提供了一种结束线程的优雅方法。Java.lang.Thread类有一个用来强制结束掉线程的stop()方法。但是stop方法已经不建议使用(deprecated),原因是stop()方法会使实例丧失安全性的保障。使用stop()方法时,线程会抛出java.lang.ThreadDeath异常而马上结束,即使该线程现在正在执行灵界区间(例如synchronized方法的中间),也会马上结束。
public class CountupThread extends Thread {
private boolean isShutdown = false;
private int count = 0;
@Override
public void run() {
try {
while (isShutdown) {
doWork();
}
} catch (InterruptedException e) {
} finally {
doShutdown();
}
}
public void shutdownReqeust() {
this.isShutdown = true;
interrupt();
}
private void doShutdown() {
System.out.println("doShutdown: current count is " + this.count);
}
private void doWork() throws InterruptedException {
System.out.println("curren count is " + ++count);
Thread.sleep(500);
}
public static void main(String[] args) {
System.out.println("main Begin.");
CountupThread countupThread = new CountupThread();
countupThread.start();
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
}
System.out.println("main : shutdown request.");
countupThread.shutdownReqeust();
System.out.println("main : join");
// 等待线程结束
try {
countupThread.join();
} catch (InterruptedException e) {
}
System.out.println("main End.");
}
}
Thread-Specific Storage Pattern
Thread-Specific Storage Pattern就是“线程独有的存储库”、“针对每个线程提供的内存空间”的意义。java.lang.ThreadLocal的实例可以想象成一种集合架构(collection)或许会比较好理解。ThreadLocal的实例只有一个,管理多个对象。
public class Log {
private static final ThreadLocal<TSLog> tsLogCollection = new ThreadLocal<TSLog>();
public static void println(String s) {
getTSLog().printWrite(s);
}
public static void close() {
getTSLog().close();
}
private static TSLog getTSLog() {
TSLog tsLog = tsLogCollection.get();
// 如果线程时第一次调用,新建立新文件并注册log
if (tsLog == null) {
tsLog = new TSLog(Thread.currentThread().getName() + "-log.txt");
tsLogCollection.set(tsLog);
}
return tsLog;
}
}
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class TSLog {
private PrintWriter writer;
public TSLog(String filename) {
try {
this.writer = new PrintWriter(filename);
} catch (FileNotFoundException e) {
}
}
public void printWrite(String s) {
writer.println(s);
}
public void close() {
writer.println("===========End of log===========");
writer.close();
}
}
public class ClientThread extends Thread {
public ClientThread(String name) {
super(name);
}
@Override
public void run() {
System.out.println(getName() + " Begin.");
for (int i = 0; i < 10; i++) {
Log.println("i = " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
Log.close();
System.out.println(getName() + " End.");
}
public static void main(String[] args) {
new ClientThread("Alice").start();
new ClientThread("Bobby").start();
new ClientThread("Chris").start();
}
}
