Answer the question
In order to leave comments, you need to log in
How to synchronize threads in Java?
Hello, there is a task to create a pipeline, where each worker is 1 thread. It is necessary to make so that flows process objects. I wrote the following code, but it is not very stable. Gives the correct result after a certain number of runs. Advise what can be done ( sleep cannot be used)
public class Worker extends Thread{
private int id;
private static int itemCounter;
private int current = 1;
private static Worker[] workers;
private boolean done = false;
private Worker(String name, int id) {
setName(name);
this.id = id;
}
@Override
public void run() {
try {
if (id != 0) {
synchronized (this) {
wait();
}
}
while (current <= itemCounter) {
synchronized (this) {
System.out.println(Thread.currentThread().getName() + " processing " + current + " item");
current++;
}
if (id < (workers.length - 1)) {
synchronized (workers[id + 1]) {
workers[id + 1].notify();
}
}
if (id > 0) {
synchronized (workers[id - 1]) {
workers[id - 1].notify();
}
}
synchronized (this) {
//\\ try {
// for ( int i = 1 ; i < workers.length ; i++ ) {
//
// workers[ i ].wait( );
// }
// } catch ( Exception e ){
//
// }
if (workers.length != 1) {
if (id == (workers.length - 1) && workers[id - 1].done) {
continue;
}
if (current > itemCounter) {
done = true;
break;
}
wait();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
int workerCounter = 0;
if (args.length != 2) {
System.err.println("Error, use two arguments!");
throw new Error();
} else {
try {
workerCounter = Integer.parseInt(args[0]);
itemCounter = Integer.parseInt(args[1]);
if (workerCounter <= 0 || itemCounter <= 0) {
throw new Exception();
}
} catch (Exception e) {
System.err.println("Error: Invalid args.");
System.exit(1);
}
System.out.println(workerCounter + " Workers; " + itemCounter + " Items");
workers = new Worker[workerCounter];
for (int i = 0; i < workers.length; i++) {
workers[i] = new Worker("Worker" + (i + 1), i);
}
for (int i = 1; i < workers.length; i++) {
workers[i].start();
}
workers[0].start();
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question