如何在Java多线程中从thread-2设置thread-1的布尔标志

我正在编写一个涉及三个线程的简单多线程应用程序:
Thread-1,Thread-2和main.

Thread-1是一个随机数生成器类,它产生随机双精度并提供给Thread-2.

Thread-2使用数字来计算平均值.我使用了PipedOutputStream,Thread-1使用随机数进行输入. Thread-2使用PipedInputStream来消耗随机数.

问题是::

如果Thread-2中的平均值超过1E5,我想要发出Thread-1信号以停止产生数字.我在Thread-1中有一个需要打开的布尔标志.我怎样才能做到这一点?

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Random;

//

class NumGen extends Thread {

    PipedOutputStream pos;
    DataOutputStream dos;
    boolean isDone=false;

    public NumGen(PipedOutputStream pos){
        this.pos=pos;
        dos=new DataOutputStream(pos);
    }

    public void run(){
        while (!isDone){
            Random rand = new Random();
            try {
                dos.writeDouble(rand.nextDouble()+100.0);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

class RunningAvg extends Thread {

    PipedInputStream pis;
    DataInputStream dis;
    Double avg;
    int count;
    Double runningTotal;

    public RunningAvg(PipedInputStream pis){
        this.pis=pis;
        dis=new DataInputStream(pis);
            runningTotal=0.0;
    avg=0.0;
    }

    public void run(){
        try {
        while (dis.available()>0){
            count+=1;
            runningTotal+=dis.readDouble();
                avg=runningTotal/count;
                System.out.printf("The average in count no : %s is %s%n",count,avg);
                //if avg>1E5
                 //set NumGen.isDone=true
        }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


public class InterThreadComm {

    public static void main(String[] args){


    try {
        PipedOutputStream pos= new PipedOutputStream();
        PipedInputStream pis = new PipedInputStream(pos);
        NumGen ng = new NumGen(pos);
        RunningAvg ra = new RunningAvg(pis);
        ng.start();
        ra.start();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }


}

PS:代码因为它是永远运行而不在控制台上打印任何东西,我还没弄清楚为什么!

解决方法:

你可以使用AtomicBoolean并将它传递给两个线程,Atomic类型是可访问的抛出多线程也是线程安全的.

首先声明你将isDone标记为AtomicBoolean

private AtomicBoolean isDone;

然后声明一个AtomicBoolean对象并将其传递给两个线程

PipedOutputStream pos= new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pos);
AtomicBoolean isDone = new AtomicBoolean();
NumGen ng = new NumGen(pos, isDone);
RunningAvg ra = new RunningAvg(pis, isDone);
ng.start();
ra.start();

最后,一旦你想停止编号,请让Thread-2设置isDone false.

上一篇:java – -XX的含义是什么:NewRatio和-XX:OldSize JVM标志?


下一篇:关于ios 推送功能的终极解决