How to check for functionalty with multiple threads working without synchronization

Viewed 47

Consider this code:

public class test2 {
public static void main(String[] args) throws Exception{


    Thread t1 = new Thread(new Runnable() {
        public void run() {
            for(int i = 0; i<1000000; i++) {

            }
        }
    });

    Thread t2 = new Thread(new Runnable() {
        public void run() {
            Out.println("Counter" +" "+ i);
        }
    });

    t1.start();
    t2.start();

}

}

This code is susposed to complete this task:

Implement a program in which a thread increments a counter (static field) 1000000 times. Another thread should immediately output the same counter without waiting for the end of the first thread.

Is my code right? The reason why I am asking is because the output is always 0,and I am not sure if that is right.I'm confused as how to check for functionalty of a code when there is no synchronization in play.

1 Answers

The problem is that your code is missing the required static field (e.g. i in the code given below).

class Main {
    // Counter
    static int i = 0;   

    public static void main(String[] args) throws Exception {    
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                for (i = 0; i < 1000000; i++) {

                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            public void run() {
                System.out.println("Counter" + " " + i);
            }
        });

        t1.start();
        t2.start();
    }
}

Output:

Counter 8588
Related