/** * HardExample.java * Example for COM1317 project * By Jing Shan **/ import java.util.Random; class HardExample implements Runnable{ int MyId=-1; Random myRand; MyResource pubResource; HardExample(int i, MyResource r){ MyId = i; pubResource = r; } public void run(){ System.out.println("thread "+MyId+" starts."); myRand = new Random(System.currentTimeMillis()); for(int i=0;i<10;i++){ System.out.println("begin synchronize"); synchronized (pubResource){ pubResource.increase(100); System.out.println("resource value is changed to "+ pubResource.value()); } System.out.println("end synchronize"); try{ int sleepTime = myRand.nextInt(1000); System.out.println("trying to sleep "+sleepTime +" time"); Thread.sleep(sleepTime); }catch (InterruptedException e){ System.out.println("thread "+MyId+" is interrupted"); } } System.out.println("thread"+ MyId+" terminates"); } }