Advertisement
NB52053

xxx

Sep 16th, 2017
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.14 KB | None | 0 0
  1. // Create multiple threads.
  2.  
  3.  
  4. class NewThread implements Runnable {
  5.  
  6.     String name; // name of thread
  7.     //Thread t;
  8.  
  9.     NewThread(String name) {
  10.         this.name = name;
  11.         Thread t = new Thread(this,name);
  12.         System.out.println("New thread: "+t);
  13.         t.start(); // Start the thread
  14.     }
  15.     // This is the entry point for thread.
  16.     public void run() {
  17.         try {
  18.             for(int i = 5; i > 0; i--) {
  19.                 System.out.println(name + ": " + i);
  20.                 Thread.sleep(1000);
  21.             }
  22.         } catch (InterruptedException e) {
  23.             System.out.println(name + "Interrupted");
  24.         }
  25.         System.out.println(name + " exiting.");
  26.     }
  27. }
  28.  
  29.  
  30. class MultiThreadDemo {
  31.     public static void main(String args[]) {
  32.         new NewThread("One"); // start threads
  33.         new NewThread("Two");
  34.         new NewThread("Three");
  35.         try {
  36. // wait for other threads to end
  37.             Thread.sleep(10000);
  38.         } catch (InterruptedException e) {
  39.             System.out.println("Main thread Interrupted");
  40.         }
  41.         System.out.println("Main thread exiting.");
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement