Hi,
we need to print the odd elements using the odd thread and print the even elements using the even thread:
Here i am placing the java code and output. please post a comment if you see any mistake here.
O/P:
EvenThread-->0
OddThread<--1 p="">EvenThread-->2
OddThread<--3 p="">EvenThread-->4
OddThread<--5 p="">EvenThread-->6
OddThread<--7 p="">EvenThread-->8
OddThread<--9 p="">EvenThread-->10
OddThread<--11 p="">--11>--9>--7>--5>--3>--1>
we need to print the odd elements using the odd thread and print the even elements using the even thread:
Here i am placing the java code and output. please post a comment if you see any mistake here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | package com.learning; public class PrintODDandEvenNumbersUsingThreads { public volatile static int counter = 0; public static void main(String[] args){ PrintODDandEvenNumbersUsingThreads obj = new PrintODDandEvenNumbersUsingThreads(); Thread evenThread = new EvenThreadClass(obj); Thread oddThread = new OddThreadClass(obj); evenThread.start(); oddThread.start(); } static class EvenThreadClass extends Thread{ PrintODDandEvenNumbersUsingThreads obj = null; EvenThreadClass(PrintODDandEvenNumbersUsingThreads obj){ this.obj=obj; } public void run(){ while(!Thread.currentThread().isInterrupted()){ synchronized(obj){ try{ if(counter%2==0){ System.out.println("EvenThread-->"+counter); counter++; Thread.sleep(100); obj.notify(); }else{ obj.wait(); } }catch(InterruptedException ie){ ie.printStackTrace(); }catch(Exception e){ e.printStackTrace(); } } } } } static class OddThreadClass extends Thread{ PrintODDandEvenNumbersUsingThreads obj = null; OddThreadClass(PrintODDandEvenNumbersUsingThreads obj){ this.obj=obj; } public void run(){ while(!Thread.currentThread().isInterrupted()){ synchronized(obj){ try{ if(counter%2!=0){ System.out.println("OddThread<-- span="">+counter); counter++; Thread.sleep(100); obj.notify(); }else{ obj.wait(); } }catch(InterruptedException ie){ ie.printStackTrace(); }catch(Exception e){ e.printStackTrace(); } } } } } }--> |
O/P:
EvenThread-->0
OddThread<--1 p="">EvenThread-->2
OddThread<--3 p="">EvenThread-->4
OddThread<--5 p="">EvenThread-->6
OddThread<--7 p="">EvenThread-->8
OddThread<--9 p="">EvenThread-->10
OddThread<--11 p="">--11>--9>--7>--5>--3>--1>
No comments:
Post a Comment