Thread Completion

Go down

Thread Completion Empty Thread Completion

ตั้งหัวข้อ by Admin on Tue Sep 08, 2015 8:00 am

Create a working thread.
Code:
package test;

import java.util.Random;

/**
 * @author psupawa@gmail.com
 */
class MyThread implements Runnable {
   
   private Thread aThread;
   private Random rand = new Random();

   MyThread(String threadName) {
       aThread = new Thread(this, threadName);
       System.out.println("New thread create: " + aThread);
       aThread.start();
   }

   public void run() {
      int nunNum = rand.nextInt(10);
       try {
          for (int i = nunNum; i > 0; i--) {
             System.out.println(this.aThread.getName() + " running: " + i);
             Thread.sleep(1000);
          }
       } catch (InterruptedException e) {
          System.out.println(this.aThread.getName() + " interrupted.");
       }
       System.out.println(this.aThread.getName() + " exiting.");
   }
   
   public String getName() {
      return this.aThread.getName();
   }
   
   public void join() throws InterruptedException {
      this.aThread.join();
   }
   
   public boolean isAlive() {
      return this.aThread.isAlive();
   }
}

Create a test application.
Code:
package test;

/**
 * @author psupawa@gmail.com
 */
public class Test {

   public static void main(String args[]) {
      new Test();
   }
   
   private int MAX_THREAD = 3;
   private MyThread[] myThread;
   
   public Test() {
      myThread = new MyThread[MAX_THREAD];
      for (int i=0; i<MAX_THREAD; i++) {
         myThread[i] = new MyThread("Thread#"+i);
      }

      System.out.println("Waiting for threads to finish.");
      try {
         for (int i=0; i<MAX_THREAD; i++) {
            myThread[i].join();
         }
      } catch (InterruptedException e) {
            System.out.println("Main thread Interrupted");
      }

      System.out.println("All threads completed.");
   }
}

Run result.
Code:
New thread create: Thread[Thread#0,5,main]
New thread create: Thread[Thread#1,5,main]
New thread create: Thread[Thread#2,5,main]
Waiting for threads to finish.
Thread#0 running: 6
Thread#2 running: 9
Thread#1 running: 8
Thread#0 running: 5
Thread#2 running: 8
Thread#1 running: 7
Thread#2 running: 7
Thread#0 running: 4
Thread#1 running: 6
Thread#2 running: 6
Thread#0 running: 3
Thread#1 running: 5
Thread#2 running: 5
Thread#0 running: 2
Thread#1 running: 4
Thread#2 running: 4
Thread#0 running: 1
Thread#1 running: 3
Thread#0 exiting.
Thread#2 running: 3
Thread#1 running: 2
Thread#2 running: 2
Thread#1 running: 1
Thread#2 running: 1
Thread#1 exiting.
Thread#2 exiting.
All threads completed.

Admin
Admin

จำนวนข้อความ : 13
Join date : 29/01/2014

http://maithai.thai-forum.net

ขึ้นไปข้างบน Go down

ขึ้นไปข้างบน


 
Permissions in this forum:
คุณไม่สามารถพิมพ์ตอบ