// Race2.java // wyscig class Counter { private int _val; public Counter(int n) { _val = n; } public void inc() { int n; n = _val; n = n + 1; //Thread.yield(); // !!! wymuszenie zmiany kontekstu !!! _val = n; } public void dec() { int n; n = _val; n = n - 1; _val = n; } public int value() { return _val; } } class IThread extends Thread { private Counter _cnt; public IThread(Counter c) { _cnt = c; } public void run() { for (int i = 0; i < 1000000; ++i) { _cnt.inc(); } } } class DThread extends Thread { private Counter _cnt; public DThread(Counter c) { _cnt = c; } public void run() { for (int i = 0; i < 1000000; ++i) { _cnt.dec(); } } } class Race2 { public static void main(String[] args) { Counter cnt = new Counter(0); IThread it = new IThread(cnt); DThread dt = new DThread(cnt); //it.setPriority(10); it.start(); dt.start(); try { it.join(); dt.join(); } catch(InterruptedException ie) { } System.out.println("value=" + cnt.value()); } }