做网站开发人员架构,有没有免费的推广网站,合肥做网站优化哪家好,六安电子商务网站建设参考 - P507
1. 说明
两个线程共享同一份数据,每次使用数据时,需要先判断其是否在合理范围每次使用数据完毕使用Thread.sleep函数让线程阻塞
2.代码
class BankAccount {private int balance 100;public int getBalance() {return balance;}public void withdraw(int amou…参考 - P507
1. 说明
两个线程共享同一份数据,每次使用数据时,需要先判断其是否在合理范围每次使用数据完毕使用Thread.sleep函数让线程阻塞
2.代码
class BankAccount {private int balance 100;public int getBalance() {return balance;}public void withdraw(int amount) {balance balance - amount;}
}public class RyanAndMonicaJob implements Runnable {private BankAccount account new BankAccount();public static void main (String[] args) {RyanAndMonicaJob theJob new RyanAndMonicaJob();Thread one new Thread(theJob);Thread two new Thread(theJob);one.setName(Ryan);two.setName(Monica);one.start();two.start();}public void run() {for (int x 0; x 10; x) {makeWithdrawal(10);if(account.getBalance() 0) {System.out.println(Overdrawn!);}}}private void makeWithdrawal(int amount) {String currentThread Thread.currentThread().getName();if(account.getBalance() amount) {System.out.println(currentThread is about to withdraw);try{System.out.println(currentThread is going to sleep);Thread.sleep(500);} catch(InterruptedException ex) {ex.printStackTrace();}System.out.println(currentThread woke up.);account.withdraw(amount);System.out.println(currentThread completes the withdrawl);} else {System.out.println(Sorry, not enough for currentThread);}}
}
