Printing even and odd numbers using two different thread is very basic java interview question from Thread handling. We have discussed it here - Print Even and Odd number using two different thread . The main agenda of this post is to display even and odd numbers using Thread interrupt() mechanism. In other words, two threads will be sleeping for infinite time and and interrupt is send periodically to both thread and on interruption they wake-up and complete the task. Below are the sample code lines discussing the same.
Odd thread produced 1
Even thread produced 2
Odd thread produced 3
Even thread produced 4
Odd thread produced 5
Even thread produced 6
Odd thread produced 7
Even thread produced 8
package com.devinline.thread; public class EvenOddUsingInterrupt { public static volatile int counter; public static void main(String[] args) throws Exception { Thread even = new Thread(new EvenProducer(), "Even"); Thread odd = new Thread(new OddProducer(), "Odd"); even.start(); odd.start(); while (true) { counter++; even.interrupt(); odd.interrupt(); Thread.sleep(1000L); } } private static class EvenProducer implements Runnable { public void run() { int oldNum = 0; while (true) { try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { // System.out.println("Interrupted even thread"); } int num = counter; if (num != oldNum && num % 2 == 0) { System.out.println(Thread.currentThread().getName() + " thread produced " + num); oldNum = num; } } } } private static class OddProducer implements Runnable { public void run() { int oldNum = 0; while (true) { try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { // System.out.println("Interrupted odd thread"); } int num = counter; if (oldNum != num && num % 2 == 1) { System.out.println(Thread.currentThread().getName() + " thread produced " + num); oldNum = num; } } } } }=====Sample output=======
Odd thread produced 1
Even thread produced 2
Odd thread produced 3
Even thread produced 4
Odd thread produced 5
Even thread produced 6
Odd thread produced 7
Even thread produced 8
.......
=====================
Read also :- Different ways to solve producer consumer problem
Mua vé máy bay tại Aivivu, tham khảo
ReplyDeletevé máy bay đi Mỹ khứ hồi
vietnam airlines quốc tế
bay từ đức về việt nam mấy tiếng
lịch bay từ hà nội đến nga
các chuyến bay từ anh về việt nam
ve may bay tu phap ve viet nam
bảng giá khách sạn cách ly tphcm