[英]Thread Synchronization. Printing the values in right way
I am not able to find solution of this problem. 我无法找到这个问题的解决方案。 I am messing at some point, but not sure.
我在某些方面搞砸了,但不确定。 Kindly give your suggestions to overcome this.
请提出您的建议以克服这个问题。
Problem: 问题:
Have three arrays, each array is assigned to thread, output should be in sequence... 有三个数组,每个数组都分配给线程,输出应按顺序排列......
t1 ={1,4,7} t2 ={2,5,8} t3 ={3,6,9} t1 = {1,4,7} t2 = {2,5,8} t3 = {3,6,9}
expected output 预期产出
out = {1,2,3,4,5,6,7,8,9} out = {1,2,3,4,5,6,7,8,9}
Wht i tried: 我尝试过:
public class Worker extends Thread {
Worker next;
int[] val;
Object lock = new Object();
Worker(int[] val) {
this.val = val;
}
public void setnext(Worker next) {
this.next = next;
}
@Override
public void run() {
for (int i = 0; i < val.length; i++) {
synchronized (this) {
synchronized (next) {
System.out.println(val[i]);
next.notify();
}
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
synchronized(next){
next.notify();
}
}
}
}
and test class 和测试类
public class TestWorker {
public static void main(String[] args) throws Exception{
Worker worker1 = new Worker(new int[]{1,4,7});
Worker worker2 = new Worker(new int[]{2,5,8});
Worker worker3 = new Worker(new int[]{3,6,9});
worker1.setnext(worker3);
worker2.setnext(worker1);
worker3.setnext(worker2);
worker1.start();
worker2.start();
worker3.start();
}
}
Try my version. 试试我的版本。 Note that wait should always be used in a loop.
请注意,应始终在循环中使用wait。
public class Worker extends Thread {
int[] val;
Worker next;
boolean ready;
boolean go;
Worker(int[] val) {
this.val = val;
}
public void setNext(Worker next) {
this.next = next;
}
@Override
public void run() {
synchronized (Worker.class) {
ready = true;
Worker.class.notifyAll();
for (int i = 0; i < val.length; i++) {
try {
while (!go) {
Worker.class.wait();
}
System.out.println(val[i]);
go = false;
next.go = true;
Worker.class.notifyAll();
} catch (InterruptedException e) {
}
}
}
}
public static void main(String[] args) throws Exception {
Worker worker1 = new Worker(new int[] { 1, 4, 7 });
Worker worker2 = new Worker(new int[] { 2, 5, 8 });
Worker worker3 = new Worker(new int[] { 3, 6, 9 });
worker1.setNext(worker2);
worker2.setNext(worker3);
worker3.setNext(worker1);
worker1.start();
worker2.start();
worker3.start();
synchronized (Worker.class) {
while(!worker1.ready || !worker2.ready ||!worker3.ready ) {
Worker.class.wait();
}
worker1.go = true;
Worker.class.notifyAll();
}
}
}
output 产量
1
2
3
4
5
6
7
8
9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.