Skip to content

Instantly share code, notes, and snippets.

@HabaCo
Last active August 29, 2015 14:02
Show Gist options
  • Save HabaCo/cf089d4e68bc3cb885dc to your computer and use it in GitHub Desktop.
Save HabaCo/cf089d4e68bc3cb885dc to your computer and use it in GitHub Desktop.
Synchronized
//店鋪
public class FishShop {
int curFishAmount=0; // 魚當前的數量
int containment=10000; // 可存放魚獲最大容量(10000)
int times=0; // 交易次數
public synchronized void putFish(int amount, String fisherName){
if (curFishAmount+amount<=containment){ // 當前魚獲的存量若小於最大容量
curFishAmount+=amount; // 入存貨
System.out.println(fisherName + "進貨 "+ amount + " 條魚," + " 目前共有 " + curFishAmount + " 條魚.");
try{
Thread.sleep(50);
notify(); // 喚醒休息的漁夫 or 買家
wait(); // 交易一次就放出 synchronized 鎖
}catch(InterruptedException e){}
}
else // 倉庫爆了就慢慢等吧
try{
wait();
}catch(InterruptedException e){}
}
public synchronized void takeFish(int amount, String buyerName){
if (curFishAmount-amount >= 0){ // 當前有存貨可以購買(不為0)
curFishAmount-=amount; // 出貨
System.out.println(buyerName + "買走 "+ amount + " 條魚," + " 目前剩 " + curFishAmount + " 條魚.");
times++; // 交易次數+1
System.out.println("一共交易 " + times + " 次。"); // 驗證交易次數
try{
Thread.sleep(50);
notify(); // 喚醒休息的漁夫 or 買家
wait(); // 交易一次就放出 synchronized 鎖
}catch(InterruptedException e){}
}
else // 沒有存貨就慢慢等吧
try{
wait();
}catch(InterruptedException e){}
if (times>=100) notifyAll(); // 交易 100 次囉,還在睡覺的起床收攤回家囉
}
}
// 交易
public class Trade {
public static void main(String[] args) {
// 店舖開張
FishShop shop = new FishShop();
// 5 個漁夫
Fisher f1 = new Fisher(shop,"漁夫一");
Fisher f2 = new Fisher(shop,"漁夫二");
Fisher f3 = new Fisher(shop,"漁夫三");
Fisher f4 = new Fisher(shop,"漁夫四");
Fisher f5 = new Fisher(shop,"漁夫五");
// 5 個買家
Buyer b1 = new Buyer(shop,"買家1號");
Buyer b2 = new Buyer(shop,"買家2號");
Buyer b3 = new Buyer(shop,"買家3號");
Buyer b4 = new Buyer(shop,"買家4號");
Buyer b5 = new Buyer(shop,"買家5號");
// 5個漁夫捕魚去
new Thread(f1).start();
new Thread(f2).start();
new Thread(f3).start();
new Thread(f4).start();
new Thread(f5).start();
// 5個買家在逛街
new Thread(b1).start();
new Thread(b2).start();
new Thread(b3).start();
new Thread(b4).start();
new Thread(b5).start();
}
}
// 買家
public class Buyer implements Runnable{
FishShop shop; // 店舖的代表
String buyerName; // 買家的名字
boolean canTake = true; // 可以買嗎
// 將店鋪資訊傳入
Buyer(FishShop f, String s){
shop = f;
buyerName = s;
}
public void run() {
while (canTake){ // 如果有存貨可以買
shop.takeFish(1000, buyerName); // 打包帶走
if (shop.times>=100) // 如果交易 100 次
canTake=false; // 不給買
}
}
}
// 漁夫
public class Fisher implements Runnable {
FishShop shop; // 店舖的代表
String fisherName; // 漁夫名字
boolean canPut = true; // 可否繼續入倉
// 將店鋪資訊傳入
Fisher(FishShop f, String s){
shop = f;
fisherName = s;
}
public void run() {
while (canPut){ // 如果可以繼續入倉
shop.putFish(1000, fisherName); // 丟進倉庫
if (shop.times==100) // 如果交易 100 次了
canPut=false; // 不給進貨
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment