第七章 Thread-Per-Message

背景介绍:每一个消息一个线程,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) {
                }
            }
        }
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值