T
T
thatmaniscool2017-09-01 12:29:18
Java
thatmaniscool, 2017-09-01 12:29:18

How to synchronize a thread in Java?

So, first of all, I create a class that will generate a number to fill in an array.

public class IntegerGenerator {
  private static volatile int SerialGenerator = 0;
  public static int SerialNumber (){
    return SerialGenerator ++;
  }
}

After that, another method is created to work with the array, all methods are marked as synchronized.
public class MyMethods {
  private static int [] array;
  private static int size;
  private static int index = 0;
  
  // Инициализация
  public MyMethods (int size){
    this.size = size;
    array = new int [size];
    for (int i=0; i!=size; i++)
      array[i] = -1;
  }
  
  // Добавление нового значение в массив.
  public static synchronized void add (int value){
    array[index] = value;
    index = ++index % size;
  }
  // Проверка совпадения в массиве.
  public static synchronized boolean isConstain (int value){
    for (int i=0; i!=size; i++)
      if (array[i] == value)
        return true;
    return false;
  }
  
  // Показать весь массив.
  public static synchronized void ShowArray (){
    for (int i=0; i!=size; i++)
      System.out.println ("array[" + i + "] is: " + array[i]);
  }

}

And one more class for filling and editing this array.
public class MainClass {
  private static MyMethods MM = new MyMethods (1000);
  private static ExecutorService exec = Executors.newCachedThreadPool();
  
  // Внутренний класс
  public static class MyWork implements Runnable {
    public void run (){
      while (true){
        int value = IntegerGenerator.SerialNumber(); // Получаем значение от переменной.
        if (MM.isConstain(value)){
          System.out.println ("Dublicate serial: " + value); // если есть дубликаты, выводим сообщение
          System.exit(0);// и выходим
        }
        else
          MM.add(value); // если нет совпадения, добавляем значение в массив.
      }
    }
  }
  
  public static void main (String [] args){
    for (int i=0; i!=3; i++)
      exec.execute(new MyWork ()); // создаем три потока, которые будут поочередно работать с массивом.
      exec.shutdown();
    MM.ShowArray(); //  показать массив.
  }
}

As I understand it, the threads must be launched sequentially, first the first thread is processed until completion, then the second, third, etc.
As a result, the values ​​in the array should reach 3.000.
But the streams are not synchronized, and as a result, either everything is -1, or everything works inconsistently.

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