実行開始から 1 秒ごとに経過時間を出力する 1 つのスレッドと、15 秒ごとにメッセージを出力する別のスレッドがあります。最初のスレッドは、スレッド間で共有される時刻変数を更新する必要があり、時刻変数を更新するたびに時刻変数を読み取るように他のスレッドに通知します。これは私が現在持っているものです:
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();
}
}
私はスレッドに非常に慣れていないため、既に持っているものを正しく実装しているかどうかわかりません。また、別のスレッドに通知する方法がわかりません。現時点では正しい道を進んでいないように感じます。
誰かが助けてくれれば、本当に感謝しています!