一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Java多線程中線程間的通信實例詳解

Java多線程中線程間的通信實例詳解

2020-09-21 17:12Java教程網 Java教程

這篇文章主要介紹了Java多線程中線程間的通信實例詳解的相關資料,需要的朋友可以參考下

Java線程中線程間的通信

一、使用while方式來實現線程之間的通信

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.ietree.multithread.sync;
 
import java.util.ArrayList;
import java.util.List;
 
public class MyList {
  
  private volatile static List list = new ArrayList();
 
  public void add() {
    list.add("apple");
  }
 
  public int size() {
    return list.size();
  }
 
  public static void main(String[] args) {
 
    final MyList list1 = new MyList();
 
    Thread t1 = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          for (int i = 0; i < 10; i++) {
            list1.add();
            System.out.println("當前線程:" + Thread.currentThread().getName() + "添加了一個元素..");
            Thread.sleep(500);
          }
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }, "t1");
 
    Thread t2 = new Thread(new Runnable() {
      @Override
      public void run() {
        while (true) {
          if (list1.size() == 5) {
            System.out.println("當前線程收到通知:" + Thread.currentThread().getName() + " list size = 5 線程停止..");
            throw new RuntimeException();
          }
        }
      }
    }, "t2");
 
    t1.start();
    t2.start();
  }
}

程序輸出:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
Exception in thread "t2" 當前線程收到通知:t2 list size = 5 線程停止..
java.lang.RuntimeException
  at com.ietree.multithread.sync.MyList$2.run(MyList.java:43)
  at java.lang.Thread.run(Unknown Source)
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..

理解:線程Thread2不停地通過while語句檢測這個條件(list.size()==5)是否成立 ,從而實現了線程間的通信。但是這種方式會浪費CPU資源。

二、wait notfiy 方法實現多線程中線程之間的通信

使用這種方式實現線程通信需要注意:wait和notify必須配合synchronized關鍵字使用,wait方法釋放鎖,notify方法不釋放鎖。并且在這個例子中必須是Thread2先執行才可以。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.ietree.multithread.sync;
 
import java.util.ArrayList;
import java.util.List;
 
public class ListAdd3 {
  private volatile static List list = new ArrayList();
 
  public void add() {
    list.add("apple");
  }
 
  public int size() {
    return list.size();
  }
 
  public static void main(String[] args) {
 
    final ListAdd2 list2 = new ListAdd2();
 
    // 1 實例化出來一個 lock
    // 當使用wait 和 notify 的時候 , 一定要配合著synchronized關鍵字去使用
    final Object lock = new Object();
 
    Thread t1 = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          synchronized (lock) {
            for (int i = 0; i < 10; i++) {
              list2.add();
              System.out.println("當前線程:" + Thread.currentThread().getName() + "添加了一個元素..");
              Thread.sleep(500);
              if (list2.size() == 5) {
                System.out.println("已經發出通知..");
                //不釋放鎖,遇到size=5時還是繼續執行
                lock.notify();
              }
            }
          }
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
 
      }
    }, "t1");
 
    Thread t2 = new Thread(new Runnable() {
      @Override
      public void run() {
        synchronized (lock) {
          if (list2.size() != 5) {
            try {
              //釋放鎖,讓其他線程執行
              lock.wait();
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
          System.out.println("當前線程:" + Thread.currentThread().getName() + "收到通知線程停止..");
          throw new RuntimeException();
        }
      }
    }, "t2");
 
    t2.start();
    t1.start();
 
  }
}

程序輸出:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
已經發出通知..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t2收到通知線程停止..
Exception in thread "t2" java.lang.RuntimeException
  at com.ietree.multithread.sync.ListAdd3$2.run(ListAdd3.java:59)
  at java.lang.Thread.run(Unknown Source)

三、使用CountDownLatch類來實現多線程中線程之間的實時通信

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.ietree.multithread.sync;
 
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
 
public class ListAdd2 {
  private volatile static List list = new ArrayList();
 
  public void add() {
    list.add("apple");
  }
 
  public int size() {
    return list.size();
  }
 
  public static void main(String[] args) {
 
    final ListAdd2 list2 = new ListAdd2();
 
    final CountDownLatch countDownLatch = new CountDownLatch(1);
 
    Thread t1 = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          for (int i = 0; i < 10; i++) {
            list2.add();
            System.out.println("當前線程:" + Thread.currentThread().getName() + "添加了一個元素..");
            Thread.sleep(500);
            if (list2.size() == 5) {
              System.out.println("已經發出通知..");
              countDownLatch.countDown();
            }
          }
          // }
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
 
      }
    }, "t1");
 
    Thread t2 = new Thread(new Runnable() {
      @Override
      public void run() {
        if (list2.size() != 5) {
          try {
            countDownLatch.await();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        System.out.println("當前線程:" + Thread.currentThread().getName() + "收到通知線程停止..");
        throw new RuntimeException();
      }
    }, "t2");
 
    t2.start();
    t1.start();
 
  }
}

程序輸出:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
已經發出通知..
Exception in thread "t2" 當前線程:t1添加了一個元素..
當前線程:t2收到通知線程停止..
java.lang.RuntimeException
  at com.ietree.multithread.sync.ListAdd2$2.run(ListAdd2.java:56)
  at java.lang.Thread.run(Unknown Source)
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..
當前線程:t1添加了一個元素..

 四、使用多線程模擬一個隊列

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package com.ietree.multithread.sync;
 
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
 
public class MyQueue {
 
  // 1、定義一個盛裝元素集合
  private LinkedList<Object> list = new LinkedList<Object>();
 
  // 2、定義一個計數器
  private AtomicInteger count = new AtomicInteger();
 
  // 3、指定上限和下限
  private final int minSize = 0;
  private final int maxSize;
 
  // 4、構造方法初始化大小
  public MyQueue(int size) {
    this.maxSize = size;
  }
 
  // 5、初始化一個對象用于加鎖
  private Object lock = new Object();
 
  // put(anObject): 把anObject加到BlockingQueue里,如果BlockQueue沒有空間,則調用此方法的線程被阻斷,直到BlockingQueue里面有空間再繼續.
  public void put(Object obj) {
    synchronized (lock) {
      if (count.get() == this.maxSize) {
        try {
          lock.wait();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      // 1、加入元素
      list.add(obj);
      // 2、計數器累加
      count.incrementAndGet();
      // 3、通知(喚醒)另外一個線程
      lock.notify();
      System.out.println("新加入的元素為:" + obj);
    }
  }
 
  // take: 取走BlockingQueue里排在首位的對象,若BlockingQueue為空,阻斷進入等待狀態直到BlockingQueue有新的數據被加入.
  public Object take() {
    Object ret = null;
    synchronized (lock) {
      while (count.get() == this.minSize) {
        try {
          lock.wait();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      // 1、做移除元素操作
      ret = list.removeFirst();
      // 2、計數器作遞減操作
      count.decrementAndGet();
      // 3、喚醒另外一個操作
      lock.notify();
    }
 
    return ret;
  }
 
  // 獲取長度
  public int getSize() {
    return this.count.get();
  }
 
  public static void main(String[] args) {
 
    final MyQueue mq = new MyQueue(5);
    mq.put("a");
    mq.put("b");
    mq.put("c");
    mq.put("d");
    mq.put("e");
 
    System.out.println("當前容器的長度:" + mq.getSize());
 
    Thread t1 = new Thread(new Runnable() {
      @Override
      public void run() {
        mq.put("f");
        mq.put("g");
      }
    }, "t1");
 
    t1.start();
 
    Thread t2 = new Thread(new Runnable() {
      @Override
      public void run() {
        Object o1 = mq.take();
        System.out.println("移除的元素為:" + o1);
        Object o2 = mq.take();
        System.out.println("移除的元素為:" + o2);
      }
    }, "t2");
 
    try {
      TimeUnit.SECONDS.sleep(2);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
 
    t2.start();
  }
}

程序輸出:

?
1
2
3
4
5
6
7
8
9
10
新加入的元素為:a
新加入的元素為:b
新加入的元素為:c
新加入的元素為:d
新加入的元素為:e
當前容器的長度:5
移除的元素為:a
移除的元素為:b
新加入的元素為:f
新加入的元素為:g

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

原文鏈接:http://www.cnblogs.com/Dylansuns/p/6718407.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 久久日本片精品AAAAA国产 | 欧美一级片观看 | 毛片小视频 | 无毒成人社区 | 午夜dj免费视频观看社区 | 免费观看国产精品 | 精品国产欧美一区二区三区成人 | 日韩一级片在线播放 | 四虎影在线永久免费观看 | 亚州综合网| 日韩亚洲国产欧美精品 | 91精品国产亚洲爽啪在线影院 | 白发在线视频播放观看免费 | 奇米影视在线视频 | 女海盗斯蒂内塔的复仇2免费观看 | 大妹子最新视频在线观看 | 小泽玛丽av无码观看 | 亚洲精品97福利在线 | 性满足久久久久久久久 | 亚洲网视频 | 国内精品福利丝袜视频_速 国内精品91久久久久 | 免费二级毛片免费完整视频 | 我们日本在线观看免费动漫下载 | 欧美大片一区 | 天天操天天射天天爽 | 成人福利免费在线观看 | 亚洲高清无码在线 视频 | 国产一级在线免费观看 | 大学生宿舍飞机 free | 无人区1免费完整观看 | 亚洲天堂男人 | 香港三级血恋3 | 精品久久久久久久国产潘金莲 | 特级一级全黄毛片免费 | 激情五色月 | 日产乱码卡1卡2卡三卡四在线 | 国产大片免费在线观看 | 国产目拍亚洲精品一区二区三区 | 欧美视频一区二区三区在线观看 | 日本老头4569gay | 青青青青青国产免费手机看视频 |