Multiple threads with notifyAll ()

I write a java program that prints seconds, and every fifth second it displays a message. This is an example output:

0 1 2 3 4 hello 5 6 7 8 9 hello 10 11 12 13 14 hello 15 16 17 18 19 hello 

How to remove printMsg boolean? Is there a better thread design that allows this?

Now, without printMsg, the program will print a few "hello" during the program for 1/10 seconds, remaining at 5, 10, 15, etc.

 class Timer { private int count = 0; private int N; private String msg; private boolean printMsg = false; public Timer(String s, int N) { msg = s; this.N = N; } public synchronized void printMsg() throws InterruptedException{ while (count % N != 0 || !printMsg) wait(); System.out.print(msg + " "); printMsg = false; } public synchronized void printTime() { printMsg = true; System.out.print(count + " "); count ++; notifyAll(); } public static void main(String[] args) { Timer t = new Timer("hello", 5); new TimerThread(t).start(); new MsgThread(t).start(); } } class TimerThread extends Thread { private Timer t; public TimerThread(Timer s) {t = s;} public void run() { try { for(;;) { t.printTime(); sleep(100); } } catch (InterruptedException e) { return; } } } class MsgThread extends Thread { private Timer t; public MsgThread(Timer s) {t = s;} public void run() { try { for(;;) { t.printMsg(); } } catch (InterruptedException e) { return; } } } 
+8
java multithreading
source share
2 answers

No need to use printMsg flag, just notifyAll when count % N == 0

 public synchronized void printMsg() throws InterruptedException { wait(); System.out.print(msg + " "); } public synchronized void printTime() { System.out.print(count + " "); count++; if (count % N == 0){ notifyAll(); } } 
0
source share

One option to simplify and improve design is to use one thread instead of two threads. And let one thread take care of printing seconds, as well as the message. So reduce one thread and no need to wait () and notify. Is there a reason you want to use two streams? Code below:

 public class Timer { private int count = 0; private int N; private String msg; public Timer(String s, int N) { msg = s; this.N = N; } public synchronized void printTime() { System.out.print(count + " "); count ++; if(count % N == 0) { System.out.print(msg + " "); } } public static void main(String[] args) { Timer t = new Timer("hello", 5); new TimerThread(t).start(); } } class TimerThread extends Thread { private Timer t; public TimerThread(Timer s) {t = s;} public void run() { try { for(;;) { t.printTime(); sleep(1000); } } catch (InterruptedException e) { return; } } } 
0
source share

All Articles