J’écris un programme java qui affiche les secondes écastings et imprime un message toutes les 5 secondes. Ceci est un exemple de sortie:
0 1 2 3 4 hello 5 6 7 8 9 hello 10 11 12 13 14 hello 15 16 17 18 19 hello
Comment puis-je supprimer la variable booléenne printMsg? Y at-il une meilleure conception de fil qui permet cela?
Pour l’instant, sans printMsg, le programme imprimera plusieurs “bonjour” pendant le programme de 1/10 de seconde en restant à 5, 10, 15, etc.
class Timer { private int count = 0; private int N; private Ssortingng msg; private boolean printMsg = false; public Timer(Ssortingng 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(Ssortingng[] 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; } } }