Advertisement
Guest User

Threading Example

a guest
Feb 11th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.47 KB | None | 0 0
  1. import java.util.Random;
  2.  
  3. public class Main {
  4.     public static void main(String[] args) {
  5.         new Main();
  6.     }
  7.  
  8.     public Main() {
  9.         new ThreadOne().start();
  10.     }
  11.  
  12.     public class ThreadOne extends MyThread {
  13.         public ThreadOne() {
  14.             super("one");
  15.         }
  16.  
  17.         @Override
  18.         void startOtherThread() {
  19.             new ThreadTwo().start();
  20.         }
  21.     }
  22.  
  23.     public class ThreadTwo extends MyThread {
  24.         public ThreadTwo() {
  25.             super("two");
  26.         }
  27.  
  28.         @Override
  29.         void startOtherThread() {
  30.             new ThreadOne().start();
  31.         }
  32.     }
  33.  
  34.     abstract static class MyThread extends Thread {
  35.         private static Random random = new Random();
  36.         private String name;
  37.  
  38.         public MyThread(String name) {
  39.             this.name = name;
  40.         }
  41.  
  42.         @Override
  43.         public void run() {
  44.             while (!isInterrupted()) {
  45.                 System.out.println("Thread " + name + " is running!");
  46.                 try {
  47.                     Thread.sleep(1000);
  48.                 } catch (InterruptedException e) {
  49.                     e.printStackTrace();
  50.                 }
  51.                 if (random.nextInt(3) == 0) {
  52.                     interrupt();
  53.                     System.out.println("Thread " + name + " was interrupted!");
  54.                     startOtherThread();
  55.                 }
  56.             }
  57.         }
  58.  
  59.         abstract void startOtherThread();
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement