⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 piggybankwithsync.java

📁 一个基于JADE的多AGENT问题
💻 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 + -