You need to create a class containing a static variable with the public modifier. Then start from main 2 different threads, which will randomly change this global variable until they finish. I did this:
public class MyThread extends Thread { public synchronized void Change(int a) { if (a % 2 == 0) MainClass.variable +=2; else MainClass.variable -=2; } public void run() { for(int i=0;i<10;i++) { Change(i); System.out.println("V = "+MainClass.variable+"\ti = "+i+"\t Thread Name "+this.getName()); } } }
and
public class MainClass { public static volatile int variable = 0; synchronized protected void CreateThread() { Thread task = new MyThread(); task.start(); } public static void main(String args[]) { MainClass mc=new MainClass(); mc.CreateThread(); mc.CreateThread(); } }
But it works incorrectly. It is necessary that all changes to the variable be visible on the screen, that is, if one of the threads has increased or decreased the MainClass.variable, it must display it on the screen before control passes to another stream. Otherwise, it turns out nonsense, the console displays a completely unpredictable value of MainClass.variable. What did I do wrong?