Hi
Starting to learn about Threads and locking shared resources but I have tried this out but it doesnt seem to be working, im sure I have missed something out somewhere but cannot find it
The purpose of this program is to allow exclusive access to the shared resource for one thread at a time so the results are not duplicated e.g. Thread 1 = 1, Thread 2 = 2 etc
I seem to be getting Threads with the same number (shared resource) so it obviously isnt locking the resource properly. If any one can point me in the right direction that would be great.
Shared Class:
package threads; public class Shared { private static int num = 0; public synchronized static void addToNum() { num++; } public synchronized static int getNum() { return num; } }
Threads Class:
package threads; public class Threads extends Thread { private String Tname; public Threads(String name) { Tname = name; } public void process() { Shared.addToNum(); System.out.println("Thread: " + Tname + " is number: " + Shared.getNum()); } public void run() { process(); } }
Main Class:
package threads; public class StartThreadsMain { public static void main(String[] args) { Threads t1 = new Threads("T1"); Threads t2 = new Threads("T2"); Threads t3 = new Threads("T3"); Threads t4 = new Threads("T4"); t1.start(); t2.start(); t3.start(); t4.start(); } }
Incorrect Output:
run: Thread: T3 is number: 3 Thread: T2 is number: 4 Thread: T4 is number: 4 Thread: T1 is number: 3 BUILD SUCCESSFUL (total time: 0 seconds)
Correct Output:
run: Thread: T1 is number: 1 Thread: T2 is number: 2 Thread: T3 is number: 3 Thread: T4 is number: 4 BUILD SUCCESSFUL (total time: 0 seconds)