import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java_Thread.AccountWithSyncUsingLock.Account;
public class ThreadCooperation {
private static Account account = new Account();
public static void main(String[] args){
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new DepositTask());
executor.execute(new WithdrawTask());
executor.shutdown();
System.out.println("Thread 1\t\tThread 2\t\tBalance");
}
public static class DepositTask implements Runnable{
public void run(){
try{
while(true){
account.deposit((int)(Math.random()*10+1));
Thread.sleep(1000);
}
}
catch(InterruptedException ex){
ex.printStackTrace();
}
}
}
public static class WithdrawTask implements Runnable{
public void run(){
while(true){
account.withdraw((int)(Math.random()*10)+1);
}
}
}
private static class Account{
private static Lock lock = new ReentrantLock();
private static Condition newDeposit = lock.newCondition();
private int balance = 0;
public int getBalance(){
return balance;
}
public void withdraw(int amount){
lock.lock();
try{
while(balance < amount){
System.out.println("\t\t\tWait for a deposit");
newDeposit.await();
}
balance -=amount;
System.out.println("\t\t\tWithdraw "+ amount+"\t\t" + getBalance());
}
catch(InterruptedException ex){
ex.printStackTrace();
}
finally{
lock.unlock();
}
}
public void deposit(int amount){
lock.lock();
try{
balance += amount;
System.out.println("Deposit "+ amount + "\t\t\t\t\t" + getBalance());
newDeposit.signalAll();
}
finally{
lock.unlock();
}
}
}
}
为什么声明Lock时要用static?这个例子中只创建了一个Account实例,但假如有多个Account实例的话,按道理它们之间应该是互不干扰的,但是Lock对象声明为类变量的话是不是逻辑就不对了?
从整体的代码来说这里的static是多余的,因为ThreadCooperation中的Account对象是static的,而且Account中的balance是非static的,所以如果想要达成代码中的效果,其实Lock和Condition前面的static反而会造成误导。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。