multithreading example with synchronization
here is the same example which prints counter value in sequence and every time we run it, it produces the same result.
example
class printdemo {
public void printcount() {
try {
for(int i = 5; i > 0; i--) {
system.out.println("counter --- " + i );
}
} catch (exception e) {
system.out.println("thread interrupted.");
}
}
}
class threaddemo extends thread {
private thread t;
private string threadname;
printdemo pd;
threaddemo(string name, printdemo pd) {
threadname = name;
pd = pd;
}
public void run() {
synchronized(pd) {
pd.printcount();
}
system.out.println("thread " + threadname + " exiting.");
}
public void start () {
system.out.println("starting " + threadname );
if (t == null) {
t = new thread (this, threadname);
t.start ();
}
}
}
public class testthread {
public static void main(string args[]) {
printdemo pd = new printdemo();
threaddemo t1 = new threaddemo("thread - 1 ", pd);
threaddemo t2 = new threaddemo("thread - 2 ", pd);
t1.start();
t2.start();
// wait for threads to end
try {
t1.join();
t2.join();
} catch (exception e) {
system.out.println("interrupted");
}
}
}
this produces the same result every time you run this program −
output
starting thread - 1 starting thread - 2 counter --- 5 counter --- 4 counter --- 3 counter --- 2 counter --- 1 thread thread - 1 exiting. counter --- 5 counter --- 4 counter --- 3 counter --- 2 counter --- 1 thread thread - 2 exiting.