package java_Thread;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()); }最近在学习JAVA的多线程,这是书上的例子。为什么声明Lock时要用static?这个例子中只创建了一个Account实例,但假如有多个Account实例的话,按道理它们之间应该是互不干扰的,但是Lock对象声明为类变量的话是不是逻辑就不对了?
3 回答
添加回答
举报
0/150
提交
取消