InterviewSolution
Saved Bookmarks
| 1. |
Synchronization with respect to Java multi-threading |
|
Answer» Multiple THREADS can manage their access to a shared resource USING SYNCHRONIZATION where only one thread accesses the resource at a time. There are two types of thread synchronization in Java. These are given as follows:
A program of thread synchronization is given as follows: class Demo { synchronized void display(int n) { for(int i=1;i<=5;i++) { System.out.println(n); try { Thread.sleep(400); }catch(Exception e){System.out.println(e);} } } } class Thread1 extends Thread { Demo obj; Thread1(Demo obj) { this.obj=obj; } public void run() { obj.display(8); } } class Thread2 extends Thread { Demo obj; Thread2(Demo obj) { this.obj=obj; } public void run() { obj.display(3); } } public class SynchronizationDemo { public static void main(String args[]) { Demo obj1 = new Demo(); Thread1 thr1 = new Thread1(obj1); Thread2 thr2 = new Thread2(obj1); thr1.start(); thr2.start(); } }The output of the above program is as follows: 8 8 8 8 8 3 3 3 3 3 |
|