package thread;
public class SynchronizeDemo {
public static void main(String[] args) {
Account acnt = new Account();
Thread prod = new Thread(new Producer(acnt));
Thread con = new Thread(new Consumer(acnt));
Thread mon = new Thread(new Monitor(acnt));
prod.start();
con.start();
mon.start();
}
}
class Account {
int sum = 50;
public synchronized void withDraw() {
try {
if (sum <= 0) {
this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
if (sum >= 10) {
sum -= 10;
System.out.println("Withdraw 10");
} else {
System.out.println("Withdraw " + sum);
sum -= sum;
}
}
public synchronized void Deposit() {
sum++;
System.out.println("Deposit 1");
this.notify();
}
public synchronized void printBalance() {
if (sum <= 0) {
System.out.println("No money now.");
} else {
System.out.println("Balance :" + sum);
}
}
}
class Producer implements Runnable {
Account account;
Producer(Account act) {
this.account = act;
}
public void run() {
while (true) {
account.Deposit();
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
Account account;
Consumer(Account act) {
this.account = act;
}
public void run() {
while (true) {
account.withDraw();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Monitor implements Runnable {
Account account;
Monitor(Account act) {
this.account = act;
}
public void run() {
while (true) {
account.printBalance();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
網頁
BloggerAds 廣告
標籤
- Java (96)
- Android (27)
- 演算法 (21)
- c++ (19)
- JavaScript (7)
- OpenMp (6)
- Design Pattern (4)
- 日文歌曲 (4)
- 資料結構 (4)
- Foundation Knowledge Of Programming (3)
- QUT (2)
- CodingHomeWork (1)
- Database (1)
- 英文歌詞 (1)
搜尋此網誌
2012年5月7日 星期一
Java synchronized demo (Producer-Consumer model), 同步化範例.
訂閱:
張貼留言 (Atom)
我的網誌清單
標籤
日文歌曲
(4)
股市
(7)
股票
(9)
英文歌詞
(1)
時事
(1)
硬體(hardware)
(1)
資料結構
(4)
演算法
(21)
數學(Math)
(4)
ACM
(3)
ajax
(7)
algorithms
(1)
Android
(27)
Blog Notes(部落格記事)
(6)
C
(9)
c++
(19)
CodingHomeWork
(1)
Database
(1)
Design Pattern
(4)
Foundation Knowledge Of Programming
(3)
GWT
(1)
How
(2)
J2EE
(1)
Java
(96)
Java語言
(4)
JavaScript
(7)
Leetcode
(4)
LOL
(1)
OpenMp
(6)
QUT
(2)
Uva
(2)
Yahoo知識問答
(11)
沒有留言:
張貼留言