天天看點

多線程wait,notify,synchronzied以及lock ,await,signal的用法

  今天翻開以前的筆記練了下基本多的多線程。synchronzied,notify,wait的用法,主要用flg下标去控制wait

package classForm;

public class ThreadDemo4 {

 public static void main(String[] args) {

  Res1 res1 = new Res1();

  InpThread inpThread = new InpThread(res1);

  inpThread.start();

  OutThread outThread = new OutThread(res1);

  outThread.start();

 }

}

class Res1{

 public String name;

 public String sex;

 public boolean flg=false;//flag為false戲按成未讀取值xian

//寫入線程

class InpThread extends Thread{

 public Res1 res1;

 public InpThread(Res1 res1){

  this.res1 = res1;

 @Override

 public void run() {

  int count = 0;

  while(true){

   synchronized (res1) {

     if(res1.flg){

      try {

       res1.wait();

      } catch (InterruptedException e) {

       e.printStackTrace();

      }

     }

     if(count == 0){

      res1.name="小明";

      res1.sex="男";

     }else{

      res1.name="小紅";

      res1.sex="女";

     count=(count+1)%2;

     //和wait一起使用,喚醒另外一個線程

     res1.flg=true;

     res1.notify();

    }

  }

//讀的線程

class OutThread extends Thread{

 public OutThread(Res1 res1){

     if(!res1.flg){

     //等待用flg去控制,其他代碼塊不能寫到flg裡面

     System.out.println(res1.name+"---"+res1.sex);

     res1.flg=false;

其實synchronized和lock鎖是比較類似的,下面請看lock鎖的案例

import java.util.concurrent.locks.Condition;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

public class ThreadDemo05 {

  Res2 res2 = new Res2();

  InpThread01 inpThread = new InpThread01(res2);

  OutThread01 outThread = new OutThread01(res2);

class Res2 {

 public boolean flg = false;// flag為false戲按成未讀取值xian

 public Lock lock = new ReentrantLock();// 使用lock鎖

 Condition condition = lock.newCondition();//

// 寫入線程

class InpThread01 extends Thread {

 public Res2 res2;

 public InpThread01(Res2 res2) {

  this.res2 = res2;

  while (true) {

   res2.lock.lock();//上鎖

   if (res2.flg) {

    try {

     res2.condition.await();

    } catch (InterruptedException e) {

     e.printStackTrace();

   }

   if (count == 0) {

    res2.name = "小明";

    res2.sex = "男";

   } else {

    res2.name = "小紅";

    res2.sex = "女";

   count = (count + 1) % 2;

   // 和wait一起使用,喚醒另外一個線程

   res2.flg = true;

   res2.condition.signal();

   res2.lock.unlock();//解鎖

// 讀的線程

class OutThread01 extends Thread {

 public OutThread01(Res2 res2) {

   res2.lock.lock();

    if (!res2.flg) {

     try {

      res2.condition.await();//相當于wait

     } catch (InterruptedException e) {

      e.printStackTrace();

    // 等待用flg去控制,其他代碼塊不能寫到flg裡面

    System.out.println(res2.name + "---" + res2.sex);

    res2.flg = false;

    res2.condition.signal();//類似notify

    res2.lock.unlock();//解鎖

綜上所述,wait,notify,synchronzied要一起使用,并且上鎖必須要同一對象,lock ,await,signal也是一組。他們的差別,前者相對操作簡單,是自動上鎖,自動解鎖,後者是手動上鎖解鎖。

繼續閱讀