Synchronized is a keyword use
for thread concepts. There are chances when two or more threads are trying to
access same resource. At this point, program will get stuck or hang. So to come
over this situation java has synchronized keyword.
We
just need to share those resources to synchronized block.
public class TryCatch {
public static void main(String args[]) {
CounterDemo
counterDemo = new CounterDemo();
ThreadDemo
thread1 = new ThreadDemo("Thread - 1
", counterDemo);
ThreadDemo
thread2 = new ThreadDemo("Thread - 2
", counterDemo);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
}
catch (Exception e) {
System.out.println("Interrupted");
}
}
}
class CounterDemo {
public void counterCount() {
try {
for (int i = 0; i <= 10; i++) {
System.out.println("Counter ---
" + i);
}
}
catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadDemo extends Thread {
private Thread thread;
private String threadName;
CounterDemo
counterDemo;
ThreadDemo(String
name, CounterDemo counterDemo) {
threadName = name;
this.counterDemo = counterDemo;
}
public void run() {
/*
* Try to run this code with uncomment and
comment line 53. You will see
* the difference
*/
//
counterDemo.counterCount();
synchronized (counterDemo) {
counterDemo.counterCount();
}
System.out.println("Thread " + threadName + "
running...");
}
public void start() {
System.out.println("Starting
" +
threadName);
if (thread == null) {
thread = new Thread(this, threadName);
thread.start();
}
}
}