java多线程的应用场景

场景1

假如有Thread1、Thread2、ThreaD3、Thread4四条线程分别统计C、D、E、F四个盘的大小,所有线程都统计完毕交给Thread5线程去做汇总,应当如何实现?

1)通过java.util.concurrent.Executors中的方法创建一个线程池,用这个线程池来启动线程。启动所有要启动的线程后,执行线程池的shutdown()方法,即在所有线程执行完毕后关闭线程池。然后通过线程池的isTerminated()方法,判断线程池是否已经关闭。线程池成功关闭,就意味着所有线程已经运行完毕了。

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

public class Test {  
  
    public static void main(String args[]) throws InterruptedException {  
        ExecutorService exe = Executors.newFixedThreadPool(50);  
        for (int i = 1; i <= 5; i++) {  
            exe.execute(new SubThread(i));  
        }  
        exe.shutdown();  
        while (true) {  
            if (exe.isTerminated()) {  
                System.out.println("结束了!");  
                break;  
            }  
            Thread.sleep(200);  
        }  
    }  
}
View Code

2)使用T.join,让主线程等待这几个工作线程结束

public class JoinTester01 implements Runnable {

    private String name;

    public JoinTester01(String name) {
        this.name = name;
    }

    public void run() {
        System.out.printf("%s begins: %s\n", name, new Date());
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("%s has finished: %s\n", name, new Date());
    }

    public static void main(String[] args) {
        while (true){
            Thread thread1 = new Thread(new JoinTester01("One"));
            Thread thread2 = new Thread(new JoinTester01("Two"));
            thread1.start();
            thread2.start();
            try {
                thread1.join();
                thread2.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("Main thread is finished");
        }

    }
}
View Code

场景2

经典的消费者模式的实现

 1 package com.example.demo.consumer;
 2 
 3 import java.util.LinkedList;
 4 
 5 /**
 6  *  生产者和消费者的问题
 7  *  wait、notify/notifyAll() 实现
 8  */
 9 public class Storage1 implements AbstractStorage {
10     //仓库最大容量
11     private static final int _1MB = 128;
12     private final int MAX_SIZE = 100;
13     //仓库存储的载体
14     private LinkedList list = new LinkedList();
15     //private Object object = new Object();
16     //生产产品
17     public void produce(int num){
18         //同步
19         synchronized (list){
20             //仓库剩余的容量不足以存放即将要生产的数量,暂停生产
21             while(list.size()+num > MAX_SIZE){
22                 System.out.println("【要生产的产品数量】:" + num + "\t【库存量】:"
23                         + list.size() + "\t暂时不能执行生产任务!");
24 
25                 try {
26                     //条件不满足,生产阻塞
27                     list.wait();
28                 } catch (InterruptedException e) {
29                     e.printStackTrace();
30                 }
31             }
32 
33             for(int i=0;i<num;i++){
34                 byte[] bigBytes = new byte[ _1MB];
35                 list.add(bigBytes);
36             }
37 
38             System.out.println("【已经生产产品数】:" + num + "\t【现仓储量为】:" + list.size());
39 
40             list.notifyAll();
41         }
42     }
43 
44     //消费产品
45     public void consume(int num){
46         synchronized (list){
47 
48             //不满足消费条件
49             while (num > list.size()){
50                 System.out.println("【要消费的产品数量】:" + num + "\t【库存量】:"
51                         + list.size() + "\t暂时不能执行消费任务!");
52 
53                 try {
54                     list.wait();
55                 } catch (InterruptedException e) {
56                     e.printStackTrace();
57                 }
58             }
59                 //消费条件满足,开始消费
60                 for(int i=0;i<num;i++){
61                     list.remove();
62                 }
63                 System.out.println("【已经消费产品数】:" + num + "\t【现仓储量为】:" + list.size());
64             list.notifyAll();
65         }
66     }
67 }
Storage1

 

public class Test{
    public static void main(String[] args) {
        // 仓库对象
        AbstractStorage abstractStorage = new Storage1();

        // 生产者对象
        Producer p1 = new Producer(abstractStorage);
        Producer p2 = new Producer(abstractStorage);
        Producer p3 = new Producer(abstractStorage);
        Producer p4 = new Producer(abstractStorage);
        Producer p5 = new Producer(abstractStorage);
        Producer p6 = new Producer(abstractStorage);
        Producer p7 = new Producer(abstractStorage);

        // 消费者对象
        Consumer c1 = new Consumer(abstractStorage);
        Consumer c2 = new Consumer(abstractStorage);
        Consumer c3 = new Consumer(abstractStorage);

        // 设置生产者产品生产数量
        p1.setNum(10);
        p2.setNum(10);
        p3.setNum(10);
        p4.setNum(10);
        p5.setNum(10);
        p6.setNum(10);
        p7.setNum(80);

        // 设置消费者产品消费数量
        c1.setNum(50);
        c2.setNum(20);
        c3.setNum(30);

        // 线程开始执行
        c1.start();
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        abstractStorage.test();
        c2.start();
        c3.start();

        p1.start();
        p2.start();
        p3.start();
        p4.start();
        p5.start();
        p6.start();
        p7.start();
    }
}
main function

 to be continued

posted @ 2018-08-20 18:38  jiataoqin  阅读(1283)  评论(0编辑  收藏  举报