26. ThreadPool用法与优势

2016/10/6 17:27 下午 posted in  Java

25. ThreadLocal的设计理念与作用

目的

多线程共享一个变量,可以通过public static的形式来实现。
每一个线程都有自己的共享变量,提出ThreadLocal正是解决这样的问题。
ThreadLocal类主要解决每个线程绑定自己的值,打个比方,类似全局的存放数据的盒子,盒子中可以存放每个线程的私有数据。

常用的方法

T get();

void set(T value);

protected T initialValue() {
        return null;
}

get()用来获取本地线程中存放的值,set()用来设置本地线程中的值。
覆盖initialValue()可以设定指定的初始值,若不设定,初始值默认为null。

线程变量是隔离的,即每个线程只能访问自己的值,他们有各自的初始值。

InheritableThreadLocal

使用InheritableThreadLocal可以继承父线程中的值,并可以通过覆盖childValue方法来修改继承的值。

示例

package com.cd.threadlocal;

public class Tools {

    public static ThreadLocalDefined<String> tl = new ThreadLocalDefined<String>();
    
    public Tools() {
        // TODO Auto-generated constructor stub
    }

}

package com.cd.threadlocal;

public class ThreadLocalDefined<T> extends ThreadLocal<Object> {

    @Override
    protected Object initialValue() {
        // TODO Auto-generated method stub
        return "OK";
    }

}

package com.cd.threadlocal;

public class ThreadA extends Thread {

    public ThreadA() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public void run() {
        for(int i=0; i<10; ++i){
            if(Tools.tl.get() == null){
                System.out.println("ThreadA 1st " + Tools.tl.get());
            }
            
            System.out.println(Tools.tl.get());
            Tools.tl.set("Thread A "+ i);
        }
    }
}

package com.cd.threadlocal;

public class Main {

    public Main() {
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args) {
        
        ThreadA a = new ThreadA();
        a.start();
        
        for(int i=0; i<10; ++i){
            if(Tools.tl.get() == null){
                System.out.println("Main 1st " + Tools.tl.get());
            }
            
            System.out.println(Tools.tl.get());
            Tools.tl.set("Main Thread "+i);
        }

    }

}

运行结果

OK
OK
Main Thread 0
Thread A 0
Main Thread 1
Thread A 1
Thread A 2
Main Thread 2
Thread A 3
Main Thread 3
Thread A 4
Thread A 5
Main Thread 4
Thread A 6
Main Thread 5
Thread A 7
Main Thread 6
Thread A 8
Main Thread 7
Main Thread 8
2016/10/1 16:34 下午 posted in  Java

24. 写出生产者消费者模式

参照网络上的资料,自己写了一个生产者消费者模式。

package com.cd.test;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Main {

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        
        Container container = new Container();
        
        Producer a = new Producer(container, "Wang Sir");
        Producer b = new Producer(container, "Li Sir");
        Consumer c = new Consumer(container, "Chen");
        Consumer d = new Consumer(container, "Opp");
        Consumer e = new Consumer(container, "Satoshi");
        
        service.submit(a);
        service.submit(b);
        service.submit(c);
        service.submit(d);
        service.submit(e);
    }

}

class Goods {
    int no;
    String producer;
    
    Goods(int no, String producer){
        this.no = no;
        this.producer = producer;
    }
    
    public String toString(){
        return "product :" + no + " by " + this.producer;
    }
}

class Container {
    BlockingQueue<Goods> queue = null;
    int index = 0;
    int max = 0;
    
    Container(int num){
        if(num > 0){
            queue = new ArrayBlockingQueue<Goods>(num);
            max = num;
        }
        else{
            queue = new ArrayBlockingQueue<Goods>(10);
            max = 10;
        }
    }

    Container(){
        this(10);
    }
    
    synchronized public Goods pop() throws InterruptedException{
        if(queue == null || queue.isEmpty())
            return null;
        
        Goods tmp = queue.take();
        
        return tmp;
    }
    
    synchronized public boolean push(Goods good) throws InterruptedException{
        if(queue == null || queue.size() == max)
            return false;
        
        queue.put(good);
        
        return true;
    }
}

class Producer implements Runnable{
    Container container = null;
    String producer = null;
    
    Producer(Container ct, String producer){
        this.container = ct;
        this.producer = producer;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        int index = 0;
        
        while(index < 5){
            Goods good = new Goods(index++, this.producer);
            
            try {
                container.push(good);
                System.out.println(" Produced goods :" + good.toString());
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
}

class Consumer implements Runnable{
    Container container = null;
    String producer = null;
    
    Consumer(Container ct, String producer){
        this.container = ct;
        this.producer = producer;
    }
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(true){
            Goods good;
            
            try {
                good = container.pop();
                
                System.out.println(" Consumed goods :" + good.toString());
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
    }
    
}

其中一次的运行结果

 Produced goods :product :0 by Wang Sir
 Produced goods :product :1 by Wang Sir
 Produced goods :product :2 by Wang Sir
 Produced goods :product :3 by Wang Sir
 Produced goods :product :4 by Wang Sir
 Produced goods :product :0 by Li Sir
 Produced goods :product :1 by Li Sir
 Consumed goods :product :0 by Wang Sir
 Consumed goods :product :0 by Li Sir
 Consumed goods :product :1 by Wang Sir
 Consumed goods :product :2 by Wang Sir
 Consumed goods :product :3 by Wang Sir
 Consumed goods :product :4 by Wang Sir
 Produced goods :product :2 by Li Sir
 Consumed goods :product :1 by Li Sir
 Consumed goods :product :2 by Li Sir
 Produced goods :product :3 by Li Sir
 Consumed goods :product :3 by Li Sir
 Produced goods :product :4 by Li Sir
 Consumed goods :product :4 by Li Sir

2016/10/1 14:31 下午 posted in  Java