Anu*_*jee 3 java multithreading
Assume that one thread prints "Hello" and another prints "World". I have done it successfully for one time, as follows: package threading;
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
How do I do it for multiple time printing, say for 5 times? I tried putting for loop around the synchronized block, but of no use.
这是两个相互依赖的线程,我们需要两个同步对象.它们可能是众多事物之一.一个整数,另一个对象; 一个布尔另一个对象; 两个对象; 两个信号量等等.同步技术可以是你喜欢的Monitor或Semaphore,但它们必须是两个.
我已修改您的代码以使用信号量而不是Monitor.信号量工作更透明.您可以看到获取和发布的情况.监视器甚至是更高的构造.因此同步在引擎盖下工作.
如果您对以下代码感到满意,则可以将其转换为使用监视器.
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10963 次 |
| 最近记录: |