public class Main { public static void main(String[] args) throws InterruptedException { Test test = new Test(); Thread thread1 = new Thread(() -> { try { System.out.println(test.change()); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread thread2 = new Thread(() -> { try { System.out.println(test.change()); } catch (InterruptedException e) { e.printStackTrace(); } }); thread1.start(); TimeUnit.MILLISECONDS.sleep(8); thread2.start(); } }
public class Test { private volatile int a = 0; public int change() throws InterruptedException { while (a == 0){ TimeUnit.MILLISECONDS.sleep(10); a++; } return a; } }