There is a task to get the data in this format to the console.

Left Right Left Right Left Right

Code

public class MainClass { public static void main(String[] args) throws InterruptedException { SomeHardWork someHardWork = new SomeHardWork("Левый"); SomeHardWork someHardWork2 = new SomeHardWork("Правый"); someHardWork.start(); someHardWork2.start(); } } public class SomeHardWork extends Thread { private String name; public SomeHardWork(String name) { super(name); this.name = name; } @Override public void run() { for (int i = 0 ; i<10 ; i++){ System.out.println(name); } } } 

Thank

  • Thank you. This is what you need! - elik

2 answers 2

There are several options, the easiest in my opinion (but not the most effective) is to use a global counter:

 public static class SomeHardWork extends Thread { private static final AtomicInteger counter = new AtomicInteger(); private String name; private final int number; public SomeHardWork(String name) { super(name); this.name = name; this.number = counter.getAndIncrement(); } @Override public void run() { for (int i = 0; i < 10; i++) { while (counter.get() % 2 != number) { } System.out.println(name); counter.incrementAndGet(); } } } 
  • Mm, what about "a little Thread.sleep in while "? - Regent
  • and that it will output the left right one after another ?) - elik
  • The operation is quickly performed, there is no sense in doing a context switch - Artem Konovalov

You can do with only one monitor, using wait and notify.

 public class Main { public static void main(String[] args) throws InterruptedException { Object monitor = new Object(); SomeHardWork someHardWork = new SomeHardWork("Левый", monitor); SomeHardWork someHardWork2 = new SomeHardWork("Правый", monitor); someHardWork.start(); Thread.sleep(100); //Даем возможность начать левому someHardWork2.start(); } } class SomeHardWork extends Thread { private String name; private Object monitor; public SomeHardWork(String name, Object monitor) { super(name); this.name = name; this.monitor = monitor; } @Override public void run() { for (int i = 0; i <= 10; i++) { synchronized (monitor) { System.out.println(name); monitor.notify(); try { if (i != 10) { monitor.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } } } } } 
  • but do not know how to do it through the Executor - elik
  • Thread.sleep (100); - in practice, it works as it should, but in theory it is not a solution, because situations are possible when the second thread starts working first - Artem Konovalov