waltermilner

Untitled

Oct 24th, 2015
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1.  
  2. class MyProcess implements Runnable {
  3.  
  4.   final int ID;
  5.   final int nextOne; // ID of the next Runnable process
  6.   final Thread[] threadArray; // reference to the array of threads
  7.  
  8.   MyProcess(int i, Thread[] array) {
  9.     threadArray = array;
  10.     ID = i;
  11.     nextOne = (i + 1) % Test.THREADCOUNT;
  12.   }
  13.  
  14.   @Override
  15.   public void run() { // when this runs
  16.     while (true) { // forever
  17.       {
  18.         try {
  19.           Thread.sleep(100000); // go to sleep
  20.         } catch (InterruptedException ex) { // but when interrupted
  21.           System.out.println("MyProcess id " + ID + " running"); //output message
  22.           threadArray[nextOne].interrupt(); // then interrupt the next
  23.         }
  24.       }
  25.     }
  26.  
  27.   }
  28.  
  29. }
  30.  
  31. public class Test {
  32.  
  33.   final static int THREADCOUNT = 15;
  34.  
  35.   public static void main(String args[]) {
  36.  
  37.     // an array of threads:
  38.     final Thread[] threadArray = new Thread[THREADCOUNT];
  39.     for (int i = 0; i < THREADCOUNT; i++) { // fill array with threads
  40.       // based on the set of processes
  41.       threadArray[i] = new Thread(new MyProcess(i, threadArray));
  42.     }
  43.     for (int i = 0; i < THREADCOUNT; i++) {
  44.       threadArray[i].start(); // start them all
  45.       // they will all go to sleep
  46.     }
  47.     threadArray[0].interrupt(); // wake up the first
  48.  
  49.   }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment