我正在编写一个打印秒数的java程序,每隔5秒打印一条消息。这是一个示例输出:
0 1 2 3 4 hello 5 6 7 8 9 hello 10 11 12 13 14 hello 15 16 17 18 19 hello
如何删除布尔变量printMsg?是否有更好的线程设计允许这个?
目前,如果没有printMsg,程序将打印多个"你好"在1/10秒的节目期间,住在5,10,15等。
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;
}
}
}
答案 0 :(得分:0)
简化和更好设计的一个选择是使用单线程而不是两个线程。让单线程处理打印秒和消息。这样可以减少一个线程,不需要wait()和通知。是否有任何理由要使用两个线程?代码如下:
enter code here
if (e.srcElement.localName == 'textarea') {
var scrollHeight = e.srcElement.scrollHeight;
var scrollTop = e.srcElement.scrollTop;
if (scrollTop >= 0 && screenTop <= scrollHeight) {
that.dirY = that.dirY * 5;
e.srcElement.scrollTop = scrollTop + that.dirY;
}
}
答案 1 :(得分:0)
不需要使用printMsg标记,notifyAll
时只需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();
}
}