【发布时间】:2019-08-23 16:41:18
【问题描述】:
我试图在 2 个线程之间放置 5 秒的间隔,在另一个线程之后运行一个,即假设我的第一个线程打印“X”,将会延迟 5 秒,然后另一个线程打印“Y”,再次打印 5秒延迟,然后是“X”,这会持续下去,说 30 次。
import java.lang.*;
import java.util.concurrent.TimeUnit;
class PingPong implements Runnable
{ String word;
PingPong(String s){
word = s;
}
public void run()
{
try
{
for(int i = 0; i<30; i++)
{
System.out.println(word);
Thread.sleep(100) ;
}
} catch (InterruptedException e)
{ e.printStackTrace(); }
}
public static void main(String[] args){
Runnable p1 = new PingPong("ping");
Thread t1 = new Thread(p1);
t1.start();
Runnable p2 = new PingPong("pong");
Thread t2 = new Thread(p2);
t2.start();
}
}
【问题讨论】:
-
如果两个线程同时独立运行,您希望它们如何相互了解?
-
请格式化您的问题,为什么要使用大写字母?你的尝试在哪里?我所看到的只是一个线程每 100 毫秒打印一个单词的两个实例
-
对这种任务使用观察者模式
标签: java multithreading