黑马程序员技术交流社区
标题:
多线程例子
[打印本页]
作者:
825176857
时间:
2015-7-13 17:42
标题:
多线程例子
package thread;
/**
* 多线程模拟一个存 一个取,存完通知另一个来取
*/
public class ImitateDepositDrawTheadTest {
public static void main(String[] args) {
final DepositOrWithdrawBusiness business = new DepositOrWithdrawBusiness(1000);
new Thread(new Runnable(){
@Override
public void run() {
while(true){
business.deposit();
}
}
}).start();
new Thread(new Runnable(){
@Override
public void run() {
while(true){
business.withdraw();
}
}
}).start();
}
}
class DepositOrWithdrawBusiness{
int balance = 1000;
public DepositOrWithdrawBusiness(int balance){
this.balance = balance;
}
boolean isWithdraw = false;
public synchronized void deposit(){
if(isWithdraw){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
balance = balance+300;
System.out.println(Thread.currentThread().getName()+ " deposit $300,now balance:" + balance);
isWithdraw=true;
this.notify();
}
public synchronized void withdraw(){
if(!isWithdraw){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
balance = balance-300;
System.out.println(Thread.currentThread().getName()+ " withdraw $300,now balance:" + balance);
isWithdraw=false;
this.notify();
}
}
复制代码
作者:
huangjiawei
时间:
2015-7-13 19:46
学习了,代码很清楚,一目了然
作者:
Love丶cd
时间:
2015-7-13 20:31
不错不错。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2