1. 程式人生 > >執行緒例項,執行緒池,重入鎖,佇列

執行緒例項,執行緒池,重入鎖,佇列

  1. 執行緒池

public class TestCallableAndFuture {

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        ExecutorService es = Executors.newFixedThreadPool(2);

        Callable<Integer> task1 = new Callable<Integer>(){
            @Override
            public
Integer call() throws Exception { int sum = 0; for (int i = 1; i <= 50; i++) { sum += i; } return sum; } }; Callable<Integer> task2 = new Callable<Integer>(){ @Override
public Integer call() throws Exception { int sum = 0; for (int i = 51; i <= 100; i++) { sum += i; } return sum; } }; Future<Integer> f1 = es.submit(task1); Future<Integer> f2 = es.submit(task2); //等待中。。。造成當前執行緒阻塞(waiting)
Integer result1 = f1.get();//以阻塞形式等待非同步結果 Integer result2 = f2.get(); System.out.println(result1 + result2); } }
  1. 重入鎖,讀寫鎖

public class TestReentrantReadWriteLock {

    public static void main(String[] args) {

        final MyEntity me = new MyEntity();

        Callable writeTask = new Callable(){
            @Override
            public Object call() throws Exception {
                me.setValue(111);
                return null;
            }
        };

        Callable readTask = new Callable(){
            @Override
            public Object call() throws Exception {
                me.getValue();
                return null;
            }
        };

        ExecutorService es = Executors.newFixedThreadPool(20);

        //開始
        long startTime = System.currentTimeMillis();

        for (int i = 0; i < 2; i++) {
            es.submit(writeTask);
        }


        for (int i = 0; i < 18; i++) {
            es.submit(readTask);
        }

        es.shutdown();

        while(!es.isTerminated()){
            System.out.println("未完成...");
        }

        //結束
        long endTime = System.currentTimeMillis() - startTime;

        System.out.println(endTime);

    }

}


class MyEntity{

//  private ReentrantLock locker = new ReentrantLock();

    private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();//讀寫鎖

    ReadLock rl = rwl.readLock();//獲取讀鎖

    WriteLock wl = rwl.writeLock();//獲取寫鎖


    private Integer value = 0;

    //寫
    public void setValue(Integer value) throws InterruptedException{
        wl.lock();
        try {
            Thread.sleep(1000);
            this.value = value;
        } finally{
            wl.unlock();
        }
    }

    //讀
    public Integer getValue() throws InterruptedException{
        rl.lock();
        try {
            Thread.sleep(1000);
            return this.value;
        } finally{
            rl.unlock();
        }
    }

}
  1. 佇列, 解決生產者,消費者問題

public class TestArrayBlockingQueue {

    public static void main(String[] args) {

        final BlockingQueue<Character> bq = new LinkedBlockingQueue<Character>();

        Callable task1 = new Callable() {
            @Override
            public Object call() throws Exception {
                for (char c = 'A'; c <= 'Z'; c++) {
                    bq.put(c);
                    System.out.println("Put :" + c);
                }
                return null;
            }
        };

        Callable task2 = new Callable() {
            @Override
            public Object call() throws Exception {
                for (int i = 0; i < 26; i++) {
                    System.out.println("Take :" + bq.take());
                }
                return null;
            }
        };

        ExecutorService es = Executors.newFixedThreadPool(2);

        es.submit(task1);

        es.submit(task2);

    }

}