背景介绍:每一个消息一个线程,forexample :ThreadLocal from jdk1.2 java.lang.ThreadLocal
使用场景:客户端送达的请求,由主线程来接收。而实际处理该请求,则交给其他线程负责,主线程回到继续等待其他客户端请求的状态,此时主线程会结束,然后其他线程
继续处理请求
public class Host {
private final Helper helper = new Helper();
public void request(final int count, final char c) {
System.out.println(" request(" + count + ", " + c + ") BEGIN");
new Thread() {//每次请求建立新线程处理数据
public void run() {
helper.handle(count, c);
}
}.start();
System.out.println(" request(" + count + ", " + c + ") END");
}
}
public class Helper {
public void handle(int count, char c) {
System.out.println(" handle(" + count + ", " + c + ") BEGIN");
for (int i = 0; i < count; i++) {
slowly();
System.out.print(c);
}
System.out.println("");
System.out.println(" handle(" + count + ", " + c + ") END");
}
private void slowly() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
public class ThreadPerMessage {
public static void main(String args[]) {
System.out.println("BEGIN");
Object obj = new Object();
Blackhole.enter(obj);
System.out.println("END");
}
}
class Blackhole {
public static void enter(Object obj) {
System.out.println("Step 1");
magic(obj);
System.out.println("Step 2");
synchronized (obj) {
System.out.println("Step 3 (never reached here)");
}
}
//用新线程反复获取obj锁定
public static void magic(final Object obj) {
Thread thread = new Thread() { // inner class
public void run() {
synchronized (obj) { // 在此取得obj的锁定
synchronized (this) {
this.setName("Locked"); // 不设置的话,magic方法跳不出来
this.notifyAll(); // 通知已经取得obj的锁定 让thread解除锁定
}
/*try {
this.join();//等待主线程结束,但是主线程卡死在obj上
} catch (InterruptedException e) {
}*/
while (true) {//导致主线程永远得不到obj
// 无穷循环
}
}
}
};
synchronized (thread) {
thread.setName("");
thread.start(); // 线程的启动
// Guarded Suspension模式
while (thread.getName().equals("")) {
try {
thread.wait(); // 等待新的线程取得obj的锁定
} catch (Exception e) {
}
}
}
}
}