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

前端 未结 4 889
故里飘歌
故里飘歌 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:11

    You could use AtomicBoolean and pass it to the both threads, Atomic types is accessable throw multithreading also thread safe.

    first declare you flag isDone as AtomicBoolean

    private AtomicBoolean isDone;
    

    then declare one AtomicBoolean object and pass it to the both threads

    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();
    

    finally once you want to stop generting numbers ask Thread-2 to set the isDone false.

提交回复
热议问题