?? piggybankwithsync.java
字號:
/** * PiggyBankWithSync.java: * - Demonstrate avoiding resource conflict */public class PiggyBankWithSync { private PiggyBank bank = new PiggyBank(); //Create array for 100 threads private Thread[] thread = new Thread[100]; public PiggyBankWithSync() { //Create a thread group in which all 100 threads are to be executed ThreadGroup g1 = new ThreadGroup("group"); boolean done = false; // Create and start 100 threads for (int i = 0; i < 100; i++) { //Arguments below are: (Thread Group, the Thread Object, name of thread) thread[i] = new Thread(g1, new AddAPennyThread(), "t"); thread[i].start(); } // Check that every thread have finished their execution while(!done) { //Estimate number of active threads in the thread group if (g1.activeCount() == 0) { done = true; } } } //a synchronised method used for adding one coin at the time private static synchronized void addAPenny(PiggyBank bank) { //Check current balance in the piggy bank and add a coin int newBalance = bank.getBalance() + 1; try { Thread.sleep(5); //Executing thread sleeps for a while :-) } catch (InterruptedException ex) { System.out.println(ex); } //Update balance including the recently added coin bank.setBalance(newBalance); } /******************************************* * A thread for adding a penny to the piggy bank ****************************************/ private class AddAPennyThread extends Thread { public void run() { addAPenny(bank); } } public static void main(String[] args) { PiggyBankWithSync test = new PiggyBankWithSync(); System.out.println("Using a synchronized method:\n- What is the balance?\n\tThe piggy bank contains " + test.bank.getBalance()+" coins\n"); }}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -