線程同步—打水問題

1:有一口井裏面有100桶水。java

2:有10我的,要求每個人打10桶水。ide

3:輸出第幾我的,打了第幾桶水,裏面還有幾桶水。this

   輸出:spa

        1我的打了第1桶水,裏面還有99桶水。對象

        3我的打    1                98it

           1           2               97io

           4           1               96class

            X          10              0import

 

 

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;im

public class Demo04_Water {
 public static void main(String[] args) {
  // 3:聲明一個惟一的well
  Well well = new Well();
  // 4:聲明10我的,啓動
  for (int i = 1; i <= 10; i++) {
   new Person(well, i).start();
  }
 }
}

// 1:聲明一個井對象
class Well {
 
 private int water = 100;
 private static Lock lock = new ReentrantLock();
 private static Condition con = lock.newCondition();

 public void withdraw(int n,int m) {
  lock.lock();
  try{
   water--;
   System.err.println("第" + n + "我的打了"+m+"桶水,還有" + water);
  }finally{
   lock.unlock(); 
  }
  }
 }


// 2:聲明一個Person對象,是Thread的子類
class Person extends Thread {
 // 接收Well的實例對象
 private Well well;
 private int n;

 public Person(Well w, int n) {
  this.well = w;
  this.n = n;
 }

 @Override public void run() {  for (int i = 1; i <= 10; i++) {   this.well.withdraw(n, i);  } }}

相關文章
相關標籤/搜索