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

📄 piggybankwithoutsync.java

📁 一个基于JADE的多AGENT问题
💻 JAVA
字号:
/** * PiggyBankWithoutSync.java:  * - Demonstrating a resource conflict */public class PiggyBankWithoutSync {  private PiggyBank bank = new PiggyBank();  //Create array for 100 threads  private Thread[] thread = new Thread[100];  public PiggyBankWithoutSync()   {    //Create a thread group in which all 100 threads are to be executed    ThreadGroup group = 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(group, new AddAPennyThread(), "t");      thread[i].start(); //Anropar run()    }    // Check that every thread have finished their execution    while(!done)    {          //Estimate number of active threads in the thread group      if (group.activeCount() == 0)      {        done = true;      }    }  }    //a NON-synchronised method used for adding one coin at the time  private static 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)   {    PiggyBankWithoutSync test = new PiggyBankWithoutSync();    System.out.println("Using a NON-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 + -