Quick actions

cmd+k|ctrl+k

Navigation

Languages

Access to resource which is not thread-safe

Snippet info

Language

Java

Visibility

public

Author

orochi-100

Created

2020-04-01T14:57:36Z

Updated

2020-04-01T15:07:56Z

import static java.lang.System.out;

/**
 * Main-class
 * 
 * @author orochi_100
 * @version 01.04.2020
 */
public class Main {
    private static int num = 0;
    
    /** In this main-method we are trying to increment an integer-variable to 20.000 with 2 threads in the first half and 1 thread in the other half */
    public static void main(String[] args) {
        out.println("Hello World!");
        
        new Thread(() -> {
            for (int i = 0; i < 10_000; i++) incrementNum();
        }).start();
     
        for (int i = 0; i < 10_000; i++) incrementNum();
       
       if (num == 10_000) out.println(num);
        
        num = 0;
        for (int i = 0; i < 10_000; i++) incrementNum();
        for (int i = 0; i < 10_000; i++) incrementNum();
        
        out.println(num);
    }
    
    /**Just for the sake of incrementing the static variable <code>num</code>*/
    public static void incrementNum() {
        num++;
    }
}
INFO