51,408
社区成员
发帖
与我相关
我的任务
分享
pullic class ThreadCooperation
{
public static void main(String[] args)
{
ExecutorService executor = Executors.newFixedThreadPool(2);
//DepositTask、WithdrawTask是实现了Runnable接口的类,都定义了run()方法。
executor.execute(new DepositTask());
executor.execute(new WithdrawTask());
System.out.println("...(略)");
}
}
try
{
Thread.sleep(1000);
}
catch(Exception e){}
)
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class ThreadCooperation
{
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)
newDeposit.await();
balance-=amount;
System.out.println("\t\t\tWithdraw"+amount+"\t\t"+getBalance());
}
catch(Exception e)
{
}
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();
}
}
}
private static Account account=new Account();
public static class DepositTask implements Runnable
{
public void run()
{
try
{
while(true)
{
account.deposit((int)(Math.random()*10)+1);
Thread.sleep(1000);
}
}
catch(Exception e)
{
}
}
}
public static class WithdrawTask implements Runnable
{
public void run()
{
while(true)
account.withdraw((int)(Math.random()*10)+1);
}
}
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");
}
}