gpt4 book ai didi

java - 使用java中的两个线程多次打印 "Hello"和 "world"

转载 作者:搜寻专家 更新时间:2023-11-01 04:03:00 24 4
gpt4 key购买 nike

假设一个线程打印“Hello”,另一个线程打印“World”。我做过一次成功了,如下:包线程;

public class InterThread {

public static void main(String[] args) {
MyThread mt=new MyThread();
mt.start();
synchronized(mt){
System.out.println("Hello");
try {
mt.wait();
i++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

}

class MyThread extends Thread{

public void run(){
synchronized(this){
System.out.println("World!");
notify();
}
}
}

如何进行多次打印,比如 5 次?我尝试在同步块(synchronized block)周围放置 for 循环,但没有用。

最佳答案

这里是两个相互依赖的线程,我们需要两个同步对象。它们可能是许多事情之一。一个整数,另一个对象;一个 boolean 值另一个对象;两者都反对;两个信号量等等。同步技术可以是 Monitor 或 Semaphore 任何你喜欢的方式,但它们必须是两个。

我已修改您的代码以使用信号量而不是监视器。信号量的工作更加透明。您可以看到获取和释放的发生。监视器是更高的构造。因此,Synchronized 在后台工作。

如果您对以下代码感到满意,则可以将其转换为使用监视器。

    import java.util.concurrent.Semaphore;

public class MainClass {

static Semaphore hello = new Semaphore(1);
static Semaphore world = new Semaphore(0);

public static void main(String[] args) throws InterruptedException {
MyThread mt=new MyThread();
mt.hello = hello;
mt.world = world;
mt.start();

for (int i=0; i<5; i++) {
hello.acquire(); //wait for it
System.out.println("Hello");

world.release(); //go say world
}
}
}

class MyThread extends Thread{

Semaphore hello, world;

public void run(){
try {
for(int i = 0; i<5; i++) {
world.acquire(); // wait-for it
System.out.println(" World!");

hello.release(); // go say hello
}

} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

关于java - 使用java中的两个线程多次打印 "Hello"和 "world",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16963405/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com