how to set boolean flag of thread-1 from thread-2 in Java multithreading

前端 未结 4 885
故里飘歌
故里飘歌 2020-12-21 22:32

I am writing a simple multithreaded application that involves three threads: Thread-1, Thread-2 and main.

4条回答
  •  一整个雨季
    2020-12-21 23:09

    I would have the main() routine create a new AtomicBoolean object, and I would pass references to the object to the constructors of both Thread classes. The RunningAvg.run() method can set the AtomicBoolean, and the NumGen.run() method can examine it.

    class NumGen extends Thread {
        ...
        AtomicBoolean isDone;
    
        public NumGen(PipedOutputStream pos, AtomicBoolean isDone){
            ...
            this.isDone = isDone;
        }
    
        public void run(){
            while (!isDone.get()){
                ...
            }
        }
    }
    
    class RunningAvg extends Thread {
        ...
        AtomicBoolean isDone;
    
        public RunningAvg(PipedInputStream pis, AtomicBoolean isDone){
            ...
            this.isDone = isDone;
        }
    
        public void run(){
            try {
            while (dis.available()>0){
                ...
                if (avg > 1E5) {
                    isDone.set(true);
                    ...
                }
            }
            ...
        }
    
    
    public class InterThreadComm {
    
        public static void main(String[] args){
    
        try {
            ...
            AtomicBoolean isDone = new AtomicBoolean(false);
            NumGen ng = new NumGen(pos, isDone);
            RunningAvg ra = new RunningAvg(pis, isDone);
            ...
        }
    

提交回复
热议问题