T
T
thatmaniscool2017-10-03 19:45:37
Java
thatmaniscool, 2017-10-03 19:45:37

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!");
      }
    }
  }
}

My question is, is it possible to use more threads than just two?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question