如何在Java线程中使用wait?

时间:2019-03-06 04:30:31

标签: java multithreading concurrency

我正在用Java实现并发。我有两个线程,一个线程最多可以计数20个,另一个线程可以从20开始计数。我希望第一个线程完成,然后运行第二个线程。我可以使用thread.sleep命令来执行此操作,但是第二个线程的运行速度比第一个线程慢得多。有没有办法让第一个线程运行,然后第二个线程以相同的速度运行?谢谢您的帮助。

import java.lang.*;



public class threads extends Thread{

    public static void main(String[] args) {


        addition addrunner = new addition();
        addrunner.start();
        addrunner.setName("addition");

        subtraction subrun = new subtraction();
        subrun.setName("subtraction");
        subrun.start();
    }

}

class addition extends Thread{
    public void run() {

        for(int i = 0; i<=20; i++) {
            System.out.println("Number: " + i + " - Thread name is: " + Thread.currentThread().getName());

        }
    }
}


class subtraction extends Thread{
    public void run() {
        for(int i = 20; i>= 0; i--) {
            System.out.println("Number: " + i + " - Thread name is: " + Thread.currentThread().getName());
            try {
                Thread.sleep(800);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以在第二个Thread.sleep()线程中删除subtraction调用,因为这不是控制您的情况下线程执行的正确方法。

启动第一个addition线程后,您需要使用 Thread.join ,以便main线程将一直等待直到addition线程已完全完成,只有这样subtraction线程才会启动。

public class Threads extends Thread{
 public static void main(String[] args) {
        try {
            Addition addrunner = new Addition();
            addrunner.start();
            addrunner.setName("addition");
            addrunner.join(); //main thread waits here, until the addition thread has finished executing

            Subtraction subrun = new Subtraction();
            subrun.setName("subtraction");
            subrun.start();
        }catch (InterruptedException ie){
            ie.printStackTrace();
        }
    }
}

class Addition extends Thread{
    public void run() {

        for(int i = 0; i<=20; i++) {
            System.out.println("Number: " + i + " - Thread name is: " + Thread.currentThread().getName());

        }
    }
}


class Subtraction extends Thread{
    public void run() {
        for(int i = 20; i>= 0; i--) {
            System.out.println("Number: " + i + " - Thread name is: " + Thread.currentThread().getName());
        }
    }
}

输出:

Number: 0 - Thread name is: addition
Number: 1 - Thread name is: addition
Number: 2 - Thread name is: addition
Number: 3 - Thread name is: addition
...
Number: 19 - Thread name is: addition
Number: 20 - Thread name is: addition


Number: 20 - Thread name is: subtraction
Number: 19 - Thread name is: subtraction
...
Number: 3 - Thread name is: subtraction
Number: 2 - Thread name is: subtraction
Number: 1 - Thread name is: subtraction
Number: 0 - Thread name is: subtraction