/** * CountThread * first Thread class * problem of multiple threads updating a shared resource */ // (1) extends Thread public class CountThread extends Thread { private static final int GOAL_EVEN = 20; private static final int GOAL_ODD = 0; // shared resource private static int shared = 10; // inidividual resource private int id; public CountThread(int id) { this.id = id; } // (2) override run() // override the behavior of the threads @Override public void run() { if (id % 2 == 0) { // even threads: increment shared while (shared < GOAL_EVEN) { ++shared; System.out.printf("id: %d shared=%d\n", id, shared); } } else { // odd threads: decrement shared while (shared > GOAL_ODD) { --shared; System.out.printf("id: %d shared=%d\n", id, shared); } } } public static void main(String[] args) { CountThread ct1 = new CountThread(1); CountThread ct2 = new CountThread(2); // (3) have the threads start working ct1.start(); ct2.start(); // (4) wait until all threads are done try { ct1.join(); ct2.join(); } catch(InterruptedException e) { System.err.println("Threads interrupted"); e.printStackTrace(); } System.out.println("main process: Done"); } }