我需要使用3个不同的线程来打印以下模式:
线程1打印“ I”
线程2打印“ LOVE”
线程3打印“ EARTH”
I LOVE EARTH
I LOVE EARTH
I LOVE EARTH
使用wait()和notify()方法。我从下面的代码开始,但是似乎它们只打印一次,因为它们都在每个循环的第一次迭代结束时等待。
public class MultiThreading_2 {
static volatile boolean flag=false;
static volatile String word = "I";
public static void main(String[] args) throws InterruptedException {
MultiThreading_2 m = new MultiThreading_2();
Runnable a = new Runnable() {
public void run() {
if(word.equals("I"))
{
synchronized(m)
{
for(int i=1;i<=2;i++) {
if(word.equals("I")) {
System.out.println("I ");
word="LOVE";
try {
m.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
m.notify();
}
}
}
}
};
Runnable b = new Runnable() {
public void run() {
if(word.equals("LOVE"))
{
synchronized(m)
{
for(int j=1;j<=2;j++) {
if(word.equals("LOVE")) {
System.out.println("LOVE ");
word="WORLD";
try {
m.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m.notify();
}
}
}
}
}
};
Runnable c = new Runnable() {
public void run() {
if(word.equals("WORLD"))
{
synchronized(m)
{
有人可以解释如何解决这个问题吗?
慕运维8079593
沧海一幻觉
相关分类