InterviewSolution
Saved Bookmarks
| 1. |
Write a program in Java to show Thread Synchronization. |
|
Answer» Here, you can create any 2 threads and synchronize them by using the synchronized keyword. An example program is given below. Java Program to show Thread Synchronization class Table {public synchronized void display(int n) { for (int i = 1; i <= 10; i++) { System.out.println(n * i); } } } class Thread1 extends Thread { Table t; public Thread1(Table t) { this.t = t; } public void run() { t.display(5); } } class Thread2 extends Thread { Table t; public Thread2(Table t) { this.t = t; } public void run() { t.display(6); } } public class Main { public static void main(String[] args) { Table table = new Table(); Thread1 th1 = new Thread1(table); Thread2 th2 = new Thread2(table); th1.start(); th2.start(); } } Output 510 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 Additional Resources
|
|