I am trying to learn about threads and I do not understand the join() method.
I have a Thread (ThreadAdd.java) that adds 1 to a static int.
public class ThreadAdd extends Thread{ public static int count; @Override public void run() { try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(ThreadAdd.class.getName()).log(Level.SEVERE, null, ex); } ThreadAdd.count++; } }
In my main method, I start 2 threads:
public static void main(String[] args) throws InterruptedException { ThreadAdd s1 = new ThreadAdd(); ThreadAdd s2 = new ThreadAdd(); s1.start();s2.start(); s1.join(); s2.join(); System.out.println(ThreadAdd.count); }
I donβt understand why in most cases the result is 2, but sometimes it returns 1.
java multithreading
damien marchand
source share