3
我有一个线程可以从执行开始每秒打印经过时间,另一个线程每15秒打印一条消息。第一个线程应该更新线程之间共享的时间变量,并在每次更新时间变量时通知其他线程读取时间变量。这是我目前的:Java通知其他线程
public class PingPong implements Runnable
{
private static final int REPETITIONS = 4;
String curName = "";
int currentTime = 0;
Thread t1;
Thread t2;
PingPong() {
t1 = new Thread(this, "Admin");
t1.start();
t2 = new Thread(this, "Admin1");
t2.start();
}
public void run() {
try {
curName = Thread.currentThread().getName();
if(curName.equals(t1.getName())){
for (int i=1; i<REPETITIONS; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
Thread.sleep(1000);
// System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getState());
System.out.println(t1.getName());
currentTime++;
}
}
/*else if(curName == t2){
System.out.println("Thread 2");
}*/
System.out.println(currentTime);
} catch (InterruptedException e) {
return; // end this thread
}
}
public static void main(String[] args) {
new PingPong();
}
}
我是非常新的线程,我不知道如果我正在实施我已经正确的。另外,我不知道如何通知另一个线程。我觉得我现在不在正确的道路上。
如果有人有任何帮助,它真的很感激!
我的问题正确地得到你的问题,以及我从你的问题中了解到的是你需要'线程来沟通自己'。查看[Java并发](http://www.vogella.com/articles/JavaConcurrency/article.html)和[Java Callable](http://www.journaldev.com/1090/java-callable-future-example ) –