Writing a program with 2 threads which prints alternatively

后端 未结 14 1509
没有蜡笔的小新
没有蜡笔的小新 2020-12-31 20:47

I got asked this question recently in an interview.

Write a program with two threads (A and B), where A prints 1 , B prints 2 and so on until 50 is r

相关标签:
14条回答
  • 2020-12-31 21:11

    This was the simplest solution, I was able to think of. It uses a synchronized method and uses the notify() and the wait() to alternatively print the numbers. Hope it helps. :)

     public class program implements Runnable
        {
            static int count =1;
            private static final int MAX_COUNT = 50;
            public synchronized void print ()
            {
                System.out.println(Thread.currentThread().getName() + " is printing " + count);
                count++;
                notify();
                try{
                    if(count>MAX_COUNT)
                        return;
                    wait();
                }catch (InterruptedException e){ 
                    e.printStackTrace();
                }
            }
            public void run()
            {
                for(int i=0;i<MAX_COUNT/2;i++)
                {
                    print();
    
                }
            }
    
            public static void main(String[] args) {
    
                program x= new program();
                Thread t0= new Thread(x);
                Thread t1=  new Thread(x);
                t0.start();
                try
                {
                    Thread.sleep(1);
                } catch (InterruptedException e){
                    e.printStackTrace();
                }
                t1.start();     
            }
    
    
        }
    
    0 讨论(0)
  • 2020-12-31 21:11
    public class Testing implements Runnable {
    private static int counter = 1;
    private static final Object lock = new Object();
    
    public static void main(String[] args)  {
    
        Thread t1 = new Thread(new Testing(), "1");
        t1.start();
        Thread t2 = new Thread(new Testing(), "2");
        t2.start();
    
    }
    
    @Override
    public void run() {
        while (counter<=100) {
            synchronized (lock) {
                if (counter % 2 == 0) {
                    System.out.println(counter +" Written By Thread-"+ Thread.currentThread().getName());
                    counter++;
                    try {
                        lock.notifyAll();
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
    
                } else if (counter % 2 == 1) {
                    System.out.println(counter +" Written By Thread-"+ Thread.currentThread().getName());
                    counter++;
    
                    try {
                        lock.notifyAll();
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
    
                }
            }
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-31 21:12

    hi please find answer here...pattern ABABABAB

    package com.abhi.ThreadPractice;
    
        public class Test {
    
            public static void main(String[] args) throws InterruptedException {
    
              final Object lock = new Object();
              Thread t1 = new Thread(new Runnable() {
    
                @Override
               public void run() {
                for (int i = 0; i < 10; i++) {
    
                  synchronized (lock) {
                 // count++;
                  System.out.println("A");
                  try {
                   lock.wait();
                   lock.notify();
                  } catch (InterruptedException e) {
                   e.printStackTrace();
                  }
                 }
                }
               }
              });             
    
               Thread t2 = new Thread(new Runnable() {
    
                @Override
               public void run() {
                for (int i = 0; i < 10; i++) {
                 synchronized (lock) {
                  lock.notify();
                  //count++;
                  System.out.println("B");
                  try {
                   lock.wait();
                  } catch (InterruptedException e) {
                   e.printStackTrace();
                  }
                 }
                }
               }
              });
    
               t1.start();
              t2.start();
              t1.join();
              t2.join();
    
              }
    
            }
    
    0 讨论(0)
  • 2020-12-31 21:15

    This is another solution:

         Thread t1 = new Thread(new Runnable() {
    
            @Override
            public void run() {
                synchronized (lock) {
                    for (int i = 1; i <= 50; i += 2) {
                        System.out.println("T1=" + i);
    
                        t1turn = false;
                            try {
                                lock.notifyAll();
                                lock.wait();
                            } catch (InterruptedException e) {
                            }
                    }
                }
    
            }
        });
        Thread t2 = new Thread(new Runnable() {
    
            @Override
            public void run() {
                synchronized (lock) {
                    for (int i = 2; i <= 50; i += 2) {
                        if (t1turn)
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                            }
                        System.out.println("T2=" + i);
                        t1turn = true;
                        lock.notify();
                    }
                }
            }
        });
        t1.start();
        t2.start();
    
    0 讨论(0)
  • 2020-12-31 21:16

    May be this is still relevant:

    public class MyRunnable implements Runnable {
        public static int counter = 0;
        public static int turn = 0;
        public static Object lock = new Object();
    
        @Override
        public void run() {
            while (counter < 50) {
                synchronized (lock) {
                    if (turn == 0) {
    
                        System.out.println(counter + " from thread "
                                + Thread.currentThread().getName());
                        turn = 1;
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    } else {
                        turn = 0;
                        lock.notify();
                    }
    
                }
            }
        }
    }
    

    and then the main function

    public static void main(String[] args) {
            Thread threadA = new Thread(new MyRunnable());
            Thread threadB = new Thread(new MyRunnable ());
            threadA.start();
            threadB.start();
    }
    
    0 讨论(0)
  • 2020-12-31 21:16

    I have created a pretty basic Solution for it using the Reentrant Lock.

    package com.multithreding.trylock;
    
    import java.util.concurrent.locks.ReentrantLock;
    
    public class TryLock extends Thread {
    
        static int intitialCount = 50;          //Value till which you want to print
        int valueToSubtract = 0;                //Value by which difference you want to print the series like 1,2,3
        static ReentrantLock alternate = new ReentrantLock();
    
        public TryLock(String name) {
            this.setName(name);
        }
    
        public void run() {
            while (intitialCount > 1) {         
    
                if (valueToSubtract > 0) {
                    alternate.lock();
                    intitialCount = intitialCount - valueToSubtract;
                    valueToSubtract = 0;
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("value Subtracted " + intitialCount + " by the Thread" + this.getName());
                    alternate.unlock();
                } else {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    valueToSubtract++;
                }
            }
    
        }
    
    }
    
    package com.multithreding.trylock;
    
    public class AlternatePrint {
    
        public static void main(String[] args) throws InterruptedException{
            //You  can add as many thread to print then in different number of series
            TryLock t1 = new TryLock("Odd One");
            TryLock t2 = new TryLock("Even Value");
            t1.start();
            t2.start();
    
        }
    
    }
    

    This solution is modular as well,

    • You can add 'n' number of Threads to print the alternate series. i.e Using 3 thread at once

    • You can also print the series with more than Difference of more than 1. i.e 1,3,5 etc

    0 讨论(0)
提交回复
热议问题