Write a java program (non-gui preferred) that has a method named atomic(). demonstrate in the program how two threads can, sometimes, invoke atomic() concurrently. create a second version of the program in which the two threads cannot invoke atomic concurrently.

Respuesta :

tonb
Let's create a static counter shared by the two threads. The atomic method will increment, then decrement the counter. If concurrent invocations happen, the counter may hit 2, otherwise it should be 1.

public class HelloRunnable implements Runnable {

    public static int counter = 0;

    public static void atomic() {
        int value = ++counter;
        System.out.printf("%d ", value);
        counter = value - 1;
    }
    
    public void run() {
        int iter = 0;
        while(iter++ < 1000) {
            atomic();
        }
    }

    public static void main(String[] args) {
        (new Thread(new HelloRunnable())).start();
        (new Thread(new HelloRunnable())).start();
    }
}

You'll see an irregular pattern of 1's and 2's. Now if you add the synchronized keyword to atomic(), it'll be 1's only, because only one thread will enter atomic() at a time.

ie.:

    public synchronized static void atomic() {