实现线程等待

Implementing thread waiting

我需要编写一个 java 程序来创建一个线程来打印 1 - 3(含)的整数。打印 2 时,线程会等待第二个线程完成后再打印 3。第二个线程打印字母 3 次。

可能的输出包括: 1z2zz3 z1z2z3 12zzz3

如何等待线程完成?

我想你想等 thread.So 你可以把这一行放在你的 运行() 方法中。

Thread.sleep(1000);

因此每个线程在完成 execution.Hope 时将保持 1 秒,这将 work.Try 它并让我知道。

您可以在 Thread 对象上调用 join 方法以等待它完成。示例:

public class JoinTest implements Runnable {
    public static void main(String[] args) throws Exception {
         System.out.println("in main");
         Thread secondThread = new Thread(new JoinTest());
         secondThread.start();
         secondThread.join();
         System.out.println("join returned");
    }

    @Override
    public void run() {
        System.out.println("second thread started");
        // wait a few seconds for demonstration purposes
        try {
            Thread.sleep(3000);
        } catch(InterruptedException e) {}
        System.out.println("second thread exiting");
    }
}

注意:无论您选择扩展 Thread 还是为此实现 Runnable 都没有关系 - 任何 Thread 对象都可以加入。

输出应该是:

in main
second thread started

3 秒后:

second thread exiting
join returned

您需要某种同步机制。 通常是信号量或互斥量。

例如

Semaphore mutex = new java.util.concurrent.Semaphore(1); // 1 - means single resource

正在计算线程

{
    for (int i = 1; i < 3; i++) {
        System.print("i");
        if (i == 2) {
            // wait for other thread to finish
            mutex.acquire();
        }
    }
    System.println();  // Output newline at end.    
}

在'zzz'线程

{
    // This should be done before the other thread starts
    // and will make it wait when it wants to acquire the mutex.
    mutex.acquire();
    for (int i = 1; i < 3; i++) {
        System.print("z");
    }
    // Allow the other thread to acquire the mutex.
    mutex.release();
}

如果我的语法不是 100% java,并且没有异常处理,请原谅。

检查这个

public class Test {
    private static int number=1;
    private static int z=1;
    private static Thread t2;


    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {

            public void run() {
                for (int i = 0; i <= 20; i++) {
                    if (number == 3){
                        while (z<4);

                    }
                    System.out.print(number++);
                    if (number == 4){
                        number = 1;
                        z=1;
                    }
                }
                t2.stop();
            }
        });
        t2 = new Thread(new Runnable() {

            public void run() {
                while(true){
                   while(z<=3){
                    System.out.print("z");
                    z++;
                  }
                   System.out.print("");
                }
            }
        });
        t.start();
        t2.start();
    }
}

您可以为此目的使用 CountDownLatch,例如:

import java.util.concurrent.CountDownLatch;

public class Test {

    public static void main(String... s){

        final CountDownLatch cdl = new CountDownLatch(1);

        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println(1);
                System.out.println(2);
                try {
                    cdl.await();//wait another thread finish
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(3);
            }
        });


        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                for(int i=0;i<3;i++)
                    System.out.println("z");
                cdl.countDown();//notify all waiting threads
            }
        });

        t2.start();
        t1.start();
    }

}

输出:1zzz23、z12zz3 ...

这是您的任务的解决方案。使用 synchronized 和 wait 你可以解决这个问题。

        public static void main(String[] args) {
               new PrintingTheads().doJob();
         }

      }



    class PrintingTheads{
        private    Object objsynch= new Object();
        private  int numberofZ = 0;

        public void doJob(){
            new Thread(){
                public void run(){

                    while(true){
                      System.out.print(1); Thread.yield(); // thread yeald is here for better "mixing the number 1,2 and Z letters"
                       System.out.print(2);Thread.yield();
                       synchronized (objsynch) {
                            while(numberofZ!=3) try{objsynch.wait(10);} catch(InterruptedException e){}

                        }

                       System.out.println(3);
                       try{Thread.sleep(1000);} catch(InterruptedException e){}  // * this part is only for easy to see what happened and can be deleted
                       synchronized (objsynch) {
                          numberofZ = 0;
                          objsynch.notifyAll();
                        }
                    }

                    }

             }.start();


             new Thread(){
                 public void run(){

                     while(true){
                        synchronized (objsynch) {
                            while(numberofZ!=0) try{objsynch.wait(10);} catch(InterruptedException e){}
                        }
                        for(int i= 0;i<3;i++) {System.out.print('z');Thread.yield();}

                        synchronized (objsynch) {
                          numberofZ=3;
                          objsynch.notifyAll();
                        }
                     }
                 }

             }.start();
        }
    }