Java Code Example: two threads communicate via shared variable

The first thread waits two seconds and then assigns the value 4 to a shared variable i, which was previously initialized by the value 2. The second thread first outputs the value of the shared variable i (2), waits 3 seconds, and then outputs the i value again (4) because the first thread changed the i value in the meantime.

class FirstThread extends Thread {
    public void run() {
        try {
            sleep(2000);
            System.out.println("Thread 1: set i to 4");
            Cube.i = 4;

        } catch (InterruptedException IE) {
        }
    }
}

class SecondThread extends Thread {
    public void run() {
        try {
            System.out.println("Thread 2: i = " + Cube.i);
            sleep(3000);
            System.out.println("Thread 2: i = " + Cube.i);

        } catch (InterruptedException IE) {
        }
    }
}

public class ThreadingExample {
    static int i = 2;

    public static void main(String[] args) {
        FirstThread t1 = new FirstThread();
        SecondThread t2 = new SecondThread();

        t1.start();
        t2.start();
    }
}
Output
Thread 2: i = 2
Thread 1: set i to 4
Thread 2: i = 4