Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.javatechie.solution;
- public class Even_And_Odd_Printer_By_Two_Thread implements Runnable {
- static int count = 1;
- Object object;
- public EvenAndOddPrinter(Object object) {
- this.object = object;
- }
- @Override
- public void run() {
- //loop your loop up to your desired limit (Here i want to print even and odd up to 10)
- while (count <= 10) {
- //check if number is even
- if (count % 2 == 0 && Thread.currentThread().getName().equals("even")) {
- //synchronized object for single thread execution (to avoid data inconsistency)
- synchronized (object) {
- System.out.println(Thread.currentThread().getName() + "-" + count);
- count++;
- try {
- object.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- if (count % 2 != 0 && Thread.currentThread().getName().equals("odd")) {
- synchronized (object) {
- System.out.println(Thread.currentThread().getName() + "-" + count);
- count++;
- object.notify();
- }
- }
- }
- }
- public static void main(String[] args) {
- Object lock = new Object();
- Runnable r1 = new EvenAndOddPrinter(lock);
- Runnable r2 = new EvenAndOddPrinter(lock);
- new Thread(r1, "even").start();
- new Thread(r2, "odd").start();
- }
- }
Add Comment
Please, Sign In to add comment