Problem statement:- Print sequence 1 2 3 1 2 3....repeatedly using three different threads.
Handling three thread based on some condition will solve our problem. Here is another problem which is handling two threads - Print Even/Odd numbers using two different threads.
Below is the sample code which displays sequence 1 2 3 using three different threads.
1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 .......
======================
Read also :- Print Even and Odd number using two different threads
Handling three thread based on some condition will solve our problem. Here is another problem which is handling two threads - Print Even/Odd numbers using two different threads.
Below is the sample code which displays sequence 1 2 3 using three different threads.
package com.devinline.thread; public class SequenceDisplay { /** * devinline.com */ static Object monitor = new Object(); static boolean one = true; static boolean two = false; static boolean three = false; public static void main(String[] args) { Thread t1 = new Thread(new SequenceDisplayImpl(1)); Thread t2 = new Thread(new SequenceDisplayImpl(2)); Thread t3 = new Thread(new SequenceDisplayImpl(3)); t1.start(); t2.start(); t3.start(); } static class SequenceDisplayImpl implements Runnable { int threadId; SequenceDisplayImpl(int threadId) { this.threadId = threadId; } public void run() { print(); } private void print() { try { while (true) { Thread.sleep(500); synchronized (monitor) { if (1 == threadId) { if (!one) { monitor.wait(); } else { System.out.print(threadId + " "); one = false; two = true; three = false; monitor.notifyAll(); } } if (2 == threadId) { if (!two) { monitor.wait(); } else { System.out.print(threadId + " "); one = false; two = false; three = true; monitor.notifyAll(); } } if (3 == threadId) { if (!three) { monitor.wait(); } else { System.out.print(threadId + " "); one = true; two = false; three = false; monitor.notifyAll(); } } } } } catch (InterruptedException e) { e.printStackTrace(); } } } }=====Sample output======
1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 .......
======================
Read also :- Print Even and Odd number using two different threads
Mua vé tại Aivivu, tham khảo
ReplyDeletemua ve may bay di my
chuyến bay đưa công dân về nước
giá vé máy bay từ Vancouver về việt nam
mở chuyến bay từ nhật về việt nam
Lịch bay từ Hàn Quốc về Việt Nam hôm nay
Vé máy bay từ Đài Loan về VN
khách sạn cách ly hà nội
chuyen bay danh cho chuyen gia
Thank you for this sharing useful information.flats in gwalior
ReplyDelete