Answer the question
In order to leave comments, you need to log in
How many threads can you work with Exchanger class in Java?
For example, I will give a small program where the Exchanger class exchanges data and a small instruction is executed.
import java.util.concurrent.*;
public class MyClass {
private static final Exchanger <Boolean> exc = new Exchanger <Boolean> ();
private static final ExecutorService exec = Executors.newCachedThreadPool();
public static void main (String [] args)throws InterruptedException {
exec.execute(new MyRun ("Thread-1", true));
TimeUnit.MILLISECONDS.sleep(100);
exec.execute(new MyRun ("Thread-2", false));
TimeUnit.SECONDS.sleep(7);
exec.shutdownNow();
}
public static class MyRun implements Runnable {
private boolean key;
private String name;
public MyRun (String name, boolean key){
this.name = name;
this.key = key;
}
public void run (){
try{
while (!Thread.interrupted()){
if (key)
System.out.println (name + " works");
key = exc.exchange(key); // Обменивается данными с другим потоком.
TimeUnit.MILLISECONDS.sleep(1500);
}
} catch (InterruptedException e){
System.out.println (name + " was stopped!");
}
}
}
}
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