How to make the threads (the sequence is not important), every second deduced the inscription? It is important for synchronization to work, for one thread to go into the body of the method, while others wait, execute, then another random thread also go to execute, and all others wait again ... just like this

public class qq { public static void main ( String [] args ) throws UnknownHostException, InterruptedException { for (int i = 0; i < 5; i++) { new The().start(); } } public static class The extends Thread { final Counter c = new Counter(); @Override public synchronized void run() { while (true) { cc(); } } } public static class Counter{ public synchronized void c(){ try { Thread.sleep(1000); System.out.println("qq"); } catch (InterruptedException e) { e.printStackTrace(); } } } } 

    1 answer 1

    Your solution will not work correctly, because each thread calls its own run method. Because of this, synchronization will not work as expected. The easiest way is to create a static method and make it synchronized, or transfer the same object to each stream that has a synchronized method.

    Example of the first approach:

     public static void main(String[] args) throws Exception { for (int i = 0; i < 10; i++) { new Thread(){ @Override public void run() { while (!Thread.currentThread().isInterrupted()){ greeter(); } } }.start(); } while (!Thread.currentThread().isInterrupted()){} } private static synchronized void greeter(){ System.out.println("hello "+ Thread.currentThread().getName()); } 

    To block threads, it is also possible using synchronization tools from the java.util.concurrent package, for example, ReentrantLock , Semaphore

    • Oh Gods! you saved me, I just tried to understand why access has a lot of threads, static helped me a lot, didn’t expect that because of such nonsense everything will go awry .. thanks a lot) - alex safsafsd
    • Not at all)) - Artem Konovalov