标签:
package jun.lock; public class BankCard { protected String cardId;//银行卡号 protected int balance = 8000;//余额 public String getCardId() { return cardId; } public void setCardId(String cardId) { this.cardId = cardId; } public int getBalance() { return balance; } public void setBalance(int balance) { this.balance = balance; } } package jun.lock; import java.util.concurrent.locks.Lock; public class InCome implements Runnable{ Lock lock = null; BankCard card = null; public InCome(Lock lock, BankCard card){ this.lock = lock; this.card = card; } @Override public void run() { try { while(true){ lock.lock(); System.out.print("当前余额:" + card.getBalance()); card.setBalance(card.getBalance() + 9000); System.out.println("收入9000元,余额::" + card.getBalance()); lock.unlock(); Thread.sleep(3 * 1000); } }catch(Exception e){ e.printStackTrace(); }finally { } } } package jun.lock; import java.util.concurrent.locks.Lock; public class OutCome implements Runnable{ Lock lock = null; BankCard card = null; public OutCome(Lock lock, BankCard card){ this.lock = lock; this.card = card; } @Override public void run() { try { while(true){ lock.lock(); System.out.print("当前余额:" + card.getBalance()); card.setBalance(card.getBalance()-2500); System.out.println("消费2500,现在余额::" + card.getBalance()); lock.unlock(); Thread.sleep(1 * 1000); } }catch(Exception e){ e.printStackTrace(); }finally { } } } package jun.lock; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * * java锁的应用 * * @author xiejunbo * */ public class TestLock { public static void main(String args[]) { BankCard card = new BankCard(); Lock lock = new ReentrantLock(); ExecutorService pool = Executors.newCachedThreadPool(); //把锁对象传进线程,线程对对象进行锁定和解锁 InCome in = new InCome(lock, card); OutCome out = new OutCome(lock, card); pool.execute(in); pool.execute(out); pool.shutdown(); } } 运行结果: 当前余额:8000收入9000元,余额::17000 当前余额:17000消费2500,现在余额::14500 当前余额:14500消费2500,现在余额::12000 当前余额:12000消费2500,现在余额::9500 当前余额:9500收入9000元,余额::18500 当前余额:18500消费2500,现在余额::16000 当前余额:16000消费2500,现在余额::13500 当前余额:13500消费2500,现在余额::11000 当前余额:11000收入9000元,余额::20000 当前余额:20000消费2500,现在余额::17500 当前余额:17500消费2500,现在余额::15000 当前余额:15000消费2500,现在余额::12500 当前余额:12500收入9000元,余额::21500 当前余额:21500消费2500,现在余额::19000 当前余额:19000消费2500,现在余额::16500 当前余额:16500消费2500,现在余额::14000
标签:
原文地址:http://my.oschina.net/xiejunbo/blog/521842