Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2013
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.88 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.concurrent.Semaphore;
  3. import java.util.logging.Level;
  4. import java.util.logging.Logger;
  5.  
  6.  
  7. public class LizardsSync {
  8. /*
  9. * Set this to the number of seconds you want the lizard world to
  10. * be simulated.
  11. * Try 30 for development and 120 for more thorough testing.
  12. */
  13.  
  14. private static int WORLDEND = 120;
  15.  
  16. /*
  17. * Number of lizard threads to create
  18. */
  19. private static int NUM_LIZARDS = 20;
  20.  
  21. /*
  22. * Maximum lizards crossing at once before alerting cats
  23. */
  24. private static int MAX_LIZARD_CROSSING = 4;
  25.  
  26. /*
  27. * Maximum seconds for a lizard to sleep
  28. */
  29. private static int MAX_LIZARD_SLEEP_TIME = 3;
  30.  
  31. /*
  32. * Maximum seconds for a lizard to eat
  33. */
  34. private static int MAX_LIZARD_EAT_TIME = 5;
  35.  
  36. /*
  37. * Number of seconds it takes to cross the driveway
  38. */
  39. private static int CROSS_TIME = 2;
  40.  
  41. /*
  42. * Number of seconds for the cat to sleep.
  43. */
  44. private static int MAX_CAT_SLEEP=2;
  45.  
  46. /*
  47. * A counter that counts the number of lizzards crossing sago to monkey grass
  48. */
  49. int numCrossingSago2MonkeyGrass = 0;
  50.  
  51. /*
  52. * A counter that counts the number of lizzards crossing monkey grass to sago
  53. */
  54. int numCrossingMonkeyGrass2Sago = 0;
  55.  
  56. /**
  57. * A semaphore to protect the crossway.
  58. */
  59. Semaphore semaphoreCrossway= new Semaphore(MAX_LIZARD_CROSSING);
  60.  
  61. /**
  62. * A semaphore for mutual exclusion.
  63. */
  64. Semaphore mutex = new Semaphore(1);
  65. /*
  66. * Indicates if the world is still running.
  67. */
  68. private static boolean running = true;
  69. /*
  70. * Indicates if you want to see debug information or not.
  71. */
  72. private static boolean debug = true;
  73.  
  74. /**
  75. * The program that runs the lizard simulation.
  76. **/
  77. public void startSimulation()
  78. {
  79. ArrayList<Thread> allThreads = new ArrayList<Thread>();
  80.  
  81. // create all the lizzard threads
  82. for (int i=0; i <NUM_LIZARDS; i++)
  83. { allThreads.add(new LizardThread(i) );
  84. }
  85. // create the cat thread
  86. allThreads.add(new CatThread());
  87.  
  88. // let the world run for a while
  89. for (int i=0; i < allThreads.size(); i++)
  90. {
  91.  
  92. allThreads.get(i).start();
  93.  
  94. }
  95. sleep (WORLDEND);
  96. // terminate all threads
  97. running = false;
  98.  
  99. // wait until all threads terminate by joining all of them
  100. for (int i=0; i < allThreads.size(); i++) {
  101. try {
  102. allThreads.get(i).join();
  103. } catch (InterruptedException ex) {
  104. System.err.println ("unable to join thread, " + ex.getMessage());
  105. }
  106.  
  107. }
  108. }
  109.  
  110. /**
  111. * Models a cat thread.
  112. */
  113. public class CatThread extends Thread {
  114.  
  115.  
  116. /**
  117. * @see java.lang.Runnable.
  118. */
  119. @Override
  120. public void run()
  121. {
  122.  
  123. while (running) {
  124. // sleep for a while
  125. catSleep();
  126.  
  127. // check on lizzards
  128. checkCrossway();
  129. }
  130. }
  131.  
  132. /**
  133. * Puts cat thread to sleep for a random time.
  134. */
  135. public void catSleep()
  136. {
  137. int sleepSeconds = 1 + (int)(Math.random()*MAX_CAT_SLEEP);
  138.  
  139. if (debug) {
  140. System.out.println ("Cat is sleeping for " + sleepSeconds + " seconds.");
  141. System.out.flush();
  142. }
  143. try {
  144. sleep(sleepSeconds*1000);
  145. } catch (InterruptedException ex) {
  146. Logger.getLogger(LizardsSync.class.getName()).log(Level.SEVERE, null, ex);
  147. }
  148. if (debug) {
  149. System.out.println ("Cat awakes.");
  150. System.out.flush();
  151. }
  152. }
  153.  
  154. /**
  155. * Simulates cat checking the crossway.
  156. */
  157. public void checkCrossway()
  158. {
  159. if (numCrossingMonkeyGrass2Sago + numCrossingSago2MonkeyGrass > MAX_LIZARD_CROSSING) {
  160. System.out.println ("The cat says yum!");
  161. System.out.flush();
  162. System.exit(-1);
  163. }
  164. }
  165. }
  166.  
  167. /**
  168. * Models a lizard thread.
  169. */
  170. public class LizardThread extends Thread {
  171.  
  172. private int _id;
  173.  
  174. /**
  175. * Creates a new lizard thread.
  176. *
  177. * @param id the id assigned to the lizard thread
  178. */
  179. public LizardThread(int id)
  180. {
  181. _id = id;
  182. }
  183.  
  184. /**
  185. * @see java.lang.Runnable.
  186. */
  187. @Override
  188. public void run()
  189. {
  190.  
  191. while (running) {
  192.  
  193.  
  194. // sleep for a while in sago
  195. lizardSleep();
  196. // wait until safe to cross from sago to monkey grass
  197. sagoToMonkeyIsSafe();
  198. // cross path to monkey grass
  199. crossSagoToMonkey();
  200. //finish crossing
  201. crossedOverToMonkey();
  202. //eat in the monkey grass
  203. lizardEat();
  204. //Wait until safe to cross from monkey grass to sago
  205. monkeyToSagoIsSafe();
  206. // cross path to sago
  207. crossMonkeyToSago();
  208. //finish crossing
  209. crossedOverToSago();
  210. }
  211.  
  212. }
  213.  
  214. /**
  215. * This tests if it is safe to travel from sago to monkey.
  216. */
  217. public void sagoToMonkeyIsSafe()
  218. {
  219. if (debug) {
  220. System.out.println ("Lizard [" + _id + "] checks sago -> monkey grass.");
  221. System.out.flush();
  222. }
  223. //try to acquire a permit
  224. try {
  225. semaphoreCrossway.acquire();
  226. } catch (InterruptedException ex) {
  227. Logger.getLogger(LizardsSync.class.getName()).log(Level.SEVERE, "unable to acquire lock", ex);
  228. }
  229.  
  230. //print the number of available permits
  231. System.out.println("Lock acquired onLizard [" + _id + "]. There are " +semaphoreCrossway.availablePermits()+" permits available");
  232.  
  233. if (debug) {
  234. System.out.println ("Lizard [" + _id + "] thinks sago -> monkey grass is safe.");
  235. System.out.flush();
  236. }
  237. }
  238.  
  239. /**
  240. * Indicates that lizard crossed over to monkey grass.
  241. */
  242. public void crossedOverToMonkey()
  243. {
  244. if (debug) {
  245. System.out.println ("Lizard [" + _id + "] made it to monkey grass.");
  246. System.out.flush();
  247. }
  248. //release the semaphore
  249. semaphoreCrossway.release();
  250. //print the number of available permits
  251. System.out.println("Lock acquired onLizard [" + _id + "]. There are " +semaphoreCrossway.availablePermits()+" permits available");
  252. }
  253.  
  254.  
  255. /**
  256. * This tests if it is safe to travel from monkey to sago.
  257. */
  258. public void monkeyToSagoIsSafe()
  259. {
  260. if (debug) {
  261. System.out.println ("Lizard [" + _id + "] checks monkey grass -> sago.");
  262. System.out.flush();
  263. }
  264.  
  265. //try to acquire a permit
  266. try {
  267. semaphoreCrossway.acquire();
  268. } catch (InterruptedException ex) {
  269. Logger.getLogger(LizardsSync.class.getName()).log(Level.SEVERE, "unable to acquire lock", ex);
  270. }
  271.  
  272. //print the number of available permits
  273. System.out.println("Lock acquired on Lizard [" + _id + "]. There are " +semaphoreCrossway.availablePermits()+" permits available");
  274.  
  275. if (debug) {
  276. System.out.println ("Lizard [" + _id + "] thinks monkey grass -> sago is safe.");
  277. System.out.flush();
  278. }
  279. }
  280.  
  281. /**
  282. * Indicates that lizard crossed over to sago.
  283. */
  284. public void crossedOverToSago()
  285. {
  286. if (debug) {
  287. System.out.println ("Lizard [" + _id + "] made it to sago.");
  288. System.out.flush();
  289. }
  290. //release the semaphore
  291. semaphoreCrossway.release();
  292. //print the number of available permits
  293. System.out.println("Lock acquired on Lizard [" + _id + "]. There are " +semaphoreCrossway.availablePermits()+" permits available");
  294. }
  295.  
  296. /**
  297. * Indicates that lizard is crossing over from monkey to sago.
  298. */
  299. void crossMonkeyToSago()
  300. {
  301. if (debug) {
  302. System.out.println ("Lizard [" + _id + "] is crossing monkey grass to sago.");
  303. System.out.flush();
  304. }
  305.  
  306.  
  307. numCrossingMonkeyGrass2Sago++;
  308. System.err.print(numCrossingMonkeyGrass2Sago);
  309.  
  310.  
  311. // simulate walk
  312. try {
  313. sleep(CROSS_TIME*1000);
  314. } catch (InterruptedException ex) {
  315. Logger.getLogger(LizardsSync.class.getName()).log(Level.SEVERE, null, ex);
  316. }
  317.  
  318. numCrossingMonkeyGrass2Sago--;
  319. System.err.print(numCrossingMonkeyGrass2Sago);
  320.  
  321. }
  322.  
  323. /**
  324. * Indicates that lizard is crossing over from sago to monkey.
  325. */
  326. void crossSagoToMonkey()
  327. {
  328.  
  329. if (debug) {
  330. System.out.println ("Lizard [" + _id + "] is crossing sago to monkey grass.");
  331. System.out.flush();
  332. }
  333.  
  334. numCrossingSago2MonkeyGrass++;
  335. System.err.print(numCrossingSago2MonkeyGrass);
  336.  
  337.  
  338.  
  339. // simulate walk
  340. try {
  341. sleep(CROSS_TIME*1000);
  342. } catch (InterruptedException ex) {
  343. Logger.getLogger(LizardsSync.class.getName()).log(Level.SEVERE, null, ex);
  344. }
  345.  
  346. numCrossingSago2MonkeyGrass--;
  347. System.err.print(numCrossingSago2MonkeyGrass);
  348.  
  349. }
  350.  
  351.  
  352. /**
  353. * Puts lizard thread to sleep for a random amount of time.
  354. */
  355. public void lizardSleep()
  356. {
  357. int sleepSeconds = 1 + (int)(Math.random()*MAX_LIZARD_SLEEP_TIME);
  358.  
  359. if (debug) {
  360. System.out.println ("Lizard [" + _id + "] is sleeping for " + sleepSeconds + " seconds.");
  361. System.out.flush();
  362. }
  363. try {
  364. sleep(sleepSeconds*1000);
  365. } catch (InterruptedException ex) {
  366. Logger.getLogger(LizardsSync.class.getName()).log(Level.SEVERE, null, ex);
  367. }
  368. if (debug) {
  369. System.out.println ("Lizard [" + _id + "] awakes.");
  370. System.out.flush();
  371. }
  372. }
  373.  
  374. /**
  375. * Simulates lizard eating for a random amount of time.
  376. */
  377. public void lizardEat()
  378. {
  379. int eatSeconds = 1 + (int)(Math.random()*MAX_LIZARD_EAT_TIME);
  380.  
  381. if (debug) {
  382. System.out.println ("Lizard [" + _id + "] is eating for " + eatSeconds + " seconds.");
  383. System.out.flush();
  384. }
  385. try {
  386. sleep(eatSeconds*1000);
  387. } catch (InterruptedException ex) {
  388. Logger.getLogger(LizardsSync.class.getName()).log(Level.SEVERE, null, ex);
  389. }
  390. if (debug) {
  391. System.out.println ("Lizard [" + _id + "] finished eating.");
  392. System.out.flush();
  393. }
  394. }
  395. }
  396.  
  397. /**
  398. * Puts current thread to sleep for a specified amount of time.
  399. *
  400. * @param seconds the number of seconds to put the thread to sleep
  401. */
  402. private static void sleep(int seconds)
  403. {
  404. try {
  405. Thread.sleep(seconds*1000);
  406. } catch (InterruptedException ex) {
  407. Logger.getLogger(LizardsSync.class.getName()).log(Level.SEVERE, null, ex);
  408. }
  409. }
  410.  
  411. }
  412. ----
  413. /**
  414. * @param args the command line arguments
  415. */
  416. public static void main(String[] args) {
  417. LizardsSync myLizardsSync = new LizardsSync();
  418.  
  419. // run simulation of lizards and cats.
  420. myLizardsSync.startSimulation();
  421.  
  422. }
  423. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement