欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java多線程中線程間的通信實(shí)例詳解

 更新時(shí)間:2017年04月30日 11:41:00   投稿:lqh  
這篇文章主要介紹了Java多線程中線程間的通信實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下

Java多線程中線程間的通信

一、使用while方式來(lái)實(shí)現(xiàn)線程之間的通信

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("當(dāng)前線程:" + Thread.currentThread().getName() + "添加了一個(gè)元素..");
            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("當(dāng)前線程收到通知:" + Thread.currentThread().getName() + " list size = 5 線程停止..");
            throw new RuntimeException();
          }
        }
      }
    }, "t2");

    t1.start();
    t2.start();
  }
}

程序輸出:

當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
Exception in thread "t2" 當(dāng)前線程收到通知: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)
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..

理解:線程Thread2不停地通過(guò)while語(yǔ)句檢測(cè)這個(gè)條件(list.size()==5)是否成立 ,從而實(shí)現(xiàn)了線程間的通信。但是這種方式會(huì)浪費(fèi)CPU資源。

二、wait notfiy 方法實(shí)現(xiàn)多線程中線程之間的通信

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

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 實(shí)例化出來(lái)一個(gè) lock
    // 當(dāng)使用wait 和 notify 的時(shí)候 , 一定要配合著synchronized關(guān)鍵字去使用
    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("當(dāng)前線程:" + Thread.currentThread().getName() + "添加了一個(gè)元素..");
              Thread.sleep(500);
              if (list2.size() == 5) {
                System.out.println("已經(jīng)發(fā)出通知..");
                //不釋放鎖,遇到size=5時(shí)還是繼續(xù)執(zhí)行
                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 {
              //釋放鎖,讓其他線程執(zhí)行
              lock.wait();
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
          System.out.println("當(dāng)前線程:" + Thread.currentThread().getName() + "收到通知線程停止..");
          throw new RuntimeException();
        }
      }
    }, "t2");

    t2.start();
    t1.start();

  }
}

程序輸出:

當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
已經(jīng)發(fā)出通知..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程: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類(lèi)來(lái)實(shí)現(xiàn)多線程中線程之間的實(shí)時(shí)通信

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("當(dāng)前線程:" + Thread.currentThread().getName() + "添加了一個(gè)元素..");
            Thread.sleep(500);
            if (list2.size() == 5) {
              System.out.println("已經(jīng)發(fā)出通知..");
              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("當(dāng)前線程:" + Thread.currentThread().getName() + "收到通知線程停止..");
        throw new RuntimeException();
      }
    }, "t2");

    t2.start();
    t1.start();

  }
}

程序輸出:

當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
已經(jīng)發(fā)出通知..
Exception in thread "t2" 當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t2收到通知線程停止..
java.lang.RuntimeException
  at com.ietree.multithread.sync.ListAdd2$2.run(ListAdd2.java:56)
  at java.lang.Thread.run(Unknown Source)
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..
當(dāng)前線程:t1添加了一個(gè)元素..

 四、使用多線程模擬一個(gè)隊(duì)列

package com.ietree.multithread.sync;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class MyQueue {

  // 1、定義一個(gè)盛裝元素集合
  private LinkedList<Object> list = new LinkedList<Object>();

  // 2、定義一個(gè)計(jì)數(shù)器
  private AtomicInteger count = new AtomicInteger();

  // 3、指定上限和下限
  private final int minSize = 0;
  private final int maxSize;

  // 4、構(gòu)造方法初始化大小
  public MyQueue(int size) {
    this.maxSize = size;
  }

  // 5、初始化一個(gè)對(duì)象用于加鎖
  private Object lock = new Object();

  // put(anObject): 把a(bǔ)nObject加到BlockingQueue里,如果BlockQueue沒(méi)有空間,則調(diào)用此方法的線程被阻斷,直到BlockingQueue里面有空間再繼續(xù).
  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、計(jì)數(shù)器累加
      count.incrementAndGet();
      // 3、通知(喚醒)另外一個(gè)線程
      lock.notify();
      System.out.println("新加入的元素為:" + obj);
    }
  }

  // take: 取走BlockingQueue里排在首位的對(duì)象,若BlockingQueue為空,阻斷進(jìn)入等待狀態(tài)直到BlockingQueue有新的數(shù)據(jù)被加入.
  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、計(jì)數(shù)器作遞減操作
      count.decrementAndGet();
      // 3、喚醒另外一個(gè)操作
      lock.notify();
    }

    return ret;
  }

  // 獲取長(zhǎng)度
  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("當(dāng)前容器的長(zhǎng)度:" + 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();
  }
}

程序輸出:

新加入的元素為:a
新加入的元素為:b
新加入的元素為:c
新加入的元素為:d
新加入的元素為:e
當(dāng)前容器的長(zhǎng)度:5
移除的元素為:a
移除的元素為:b
新加入的元素為:f
新加入的元素為:g

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

相關(guān)文章

最新評(píng)論