0

私は 4 つのスレッドの魔女が 15 から 0 までの数字を印刷しています。たとえば、スレッドの実行を制御したいのですが、最初にスレッド D を終了させ、その後スレッド C を終了させ、その後スレッド B を終了させ、最後にスレッド A を終了させたいと考えています。すべて並行して行います。どうすればそれを変更できますか? 助言がありますか?

これが私のコードです:

// Suspending and resuming a thread for Java 2
class NewThread implements Runnable {
   String name; // name of thread
   Thread t;
   boolean suspendFlag;
   NewThread(String threadname) {
      name = threadname;
      t = new Thread(this, name);
      System.out.println("New thread: " + t);
      suspendFlag = false;
      t.start(); // Start the thread
   }
   // This is the entry point for thread.
   public void run() {
      try {
      for(int i = 15; i > 0; i--) {
         System.out.println(name + ": " + i);
         Thread.sleep(200);
         synchronized(this) {
            while(suspendFlag) {
               wait();
            }
          }
        }
      } catch (InterruptedException e) {
         System.out.println(name + " interrupted.");
      }
      System.out.println(name + " exiting.");
   }
   void mysuspend() {
      suspendFlag = true;
   }
   synchronized void myresume() {
      suspendFlag = false;
       notify();
   }
}

public class SuspendResume {
   public static void main(String args[]) {
      NewThread A = new NewThread("A");
      NewThread B = new NewThread("B");
      NewThread C = new NewThread("C");
      NewThread D = new NewThread("D");
//      try {
//        System.out.println("****************************************************************");
//        System.out.println(A.t.getState());
//        System.out.println(B.t.getState());
//        System.out.println(C.t.getState());
//        System.out.println(D.t.getState());
//        
//        if(D.t.isAlive())
//        {
//            System.out.println("Bla bla bla");
//        }
//            
//        Thread.sleep(1000);
//        A.mysuspend();
//        System.out.println("Suspending thread One");
//        Thread.sleep(1000);
//         A.myresume();
//         System.out.println("Resuming thread One");
//         B.mysuspend();
//         System.out.println("Suspending thread Two");
//         Thread.sleep(1000);
//         B.myresume();
//         System.out.println("Resuming thread Two");
//        
//         
//        
//      } catch (InterruptedException e) {
//         System.out.println("Main thread Interrupted");
//      }
      // wait for threads to finish
      try {
         System.out.println("Waiting for threads to finish.");
         A.t.join();
         B.t.join();
         C.t.join();
         D.t.join();
      } catch (InterruptedException e) {
         System.out.println("Main thread Interrupted");
      }
      System.out.println("Main thread exiting.");
   }
}
4

1 に答える 1