3 Threads Printing numbers in sequence

前端 未结 14 1339
不思量自难忘°
不思量自难忘° 2021-02-05 23:45

I am trying to write a simple code to print numbers in sequence. Scenario is like

Thread  Number
T1        1
T2        2
T3        3
T1        4
T2        5
T3          


        
相关标签:
14条回答
  • 2021-02-06 00:01

    Below is very generic code. i agree it is not good practice to use multiple threads for such cases

    class MultipleThreads implements Runnable {

    AtomicInteger integer;
    
    int max_val = 100;
    
    int remainder;
    int numofThreads;
    
    public MultipleThreads(AtomicInteger integer, int remainder, int numofThreads) {
        this.integer = integer;
        this.remainder = remainder;
        this.numofThreads = numofThreads;
    }
    
    @Override
    public void run() {
        while (integer.intValue() <= max_val) {
            synchronized (integer) {
    
                while (integer.intValue() % numofThreads != remainder) {
                    try {
                        integer.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (integer.intValue() > max_val)
                    break;
                System.out.println("printing :" + Thread.currentThread().getName() + " : " + integer.getAndIncrement());
                integer.notifyAll();
            }
        }
    }
    

    }

    public class ThreadSynchronization {

    public static void main(String[] args) {
        AtomicInteger at = new AtomicInteger(1);
        MultipleThreads th1 = new MultipleThreads(at, 1, 5);
        MultipleThreads th2 = new MultipleThreads(at, 2, 5);
        MultipleThreads th3 = new MultipleThreads(at, 3, 5);
        MultipleThreads th4 = new MultipleThreads(at, 4, 5);
        MultipleThreads th5 = new MultipleThreads(at, 0, 5);
    
        new Thread(th1).start();
        new Thread(th2).start();
        new Thread(th3).start();
        new Thread(th4).start();
        new Thread(th5).start();
    }
    

    }

    0 讨论(0)
  • 2021-02-06 00:02
    public class EvenOdd1 {
        //public static String str ="str1";
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            EvenOdd1 edd1 = new EvenOdd1();
    
            AbThread tr2 = new AbThread(0,edd1);
            AbThread tr3 = new AbThread(1,edd1);
            AbThread tr4 = new AbThread(2,edd1);
            tr2.start();
            tr3.start();
            tr4.start();
        }
    }
    class AbThread extends Thread {
    
            int mod;
            int mod_count=1;
            EvenOdd1 edd1;
            public static int count=1;
            int num_thread=3;
    
            public AbThread(int mod,EvenOdd1 edd1){
                this.mod = mod;
                this.edd1 = edd1;
    
            }
    
        public void run()
        {
            synchronized(edd1)
            {
                try{
                while(true){
                    while(count%num_thread!=mod)
                        edd1.wait();
    
                    if(count==30)
                        break;
    
                        print();
                      edd1.wait();
                }
                }
                catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
    
        }
    
    
        public void print()
        {
            int val = mod==1?2*mod_count:(mod==2?3*mod_count:4*mod_count);
            System.out.println(Thread.currentThread().getName() + " : " + val);
            edd1.notifyAll();
            count=count+1;
            this.mod_count++ ;
    
        }
    
    
    }
    
    0 讨论(0)
  • 2021-02-06 00:02
    public class ThreadTask implements Runnable {
    
      private int counter; 
      private int threadID;
      private final Object lock;
      private int prev;
      public ThreadTask(Object obj, int threadid, int counter){
          this.lock = obj; // monitor
          this.threadID = threadid; //id of thread  
          this.counter = counter;
          this.prev =threadid + 1;
      }
    
      public void run(){
          while(counter<100){
            synchronized(lock){ 
                if(counter == this.prev && this.threadID % 3 == this.threadID){
                    System.out.println("T" + this.threadID + " = " + this.prev);
                    this.prev = this.prev + 3;
                }
                counter++;
                lock.notifyAll();
                try{
                    lock.wait();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
          }
       }
    }
    
    public class ThreadMain {
    
        static volatile int counter = 1;
        public static void main(String args[]) throws InterruptedException{
    
           final Object lock = new Object();
           ThreadTask first = new ThreadTask(lock, 0, counter);
           ThreadTask second = new ThreadTask(lock, 1, counter);
           ThreadTask third = new ThreadTask(lock, 2, counter);
           Thread t1 = new Thread(first, "first");
           Thread t2 = new Thread(second, "second");
           Thread t3 = new Thread(third, "third");
           t1.start();
           t2.start();
           t3.start();
           t1.join();
           t2.join();
           t3.join();
       }
    }
    
    0 讨论(0)
  • 2021-02-06 00:03

    Below code uses the logic of notifying the next thread to print the number and then incrementing it by 1 and then again notifying the next thread and then go in wait state till some thread notifies it. Eg. T1 first prints the value and then makes boolean "second" true for T2 to print the next number. T2 after printing the number makes boolean "third" true for T3. T3 does the same thing by making boolean "first" true for T1 to print the next number.

    T1 -> T2 -> T3 -> T1 -> T2 -> T3 -> ........ and so on.

    public class Test{
      public static volatile int i = 0;
      public static void main(String[] args) throws InterruptedException {
        Object monitor = new Object();
        Notifier notifier = new Notifier(monitor);
        Thread thread1 = new Thread(notifier, "T1");
        Thread thread2 = new Thread(notifier, "T2");
        Thread thread3 = new Thread(notifier, "T3");
        thread1.start();
        thread2.start();
        thread3.start();
      }
    }
    
    
    
    class Notifier implements Runnable {
    
      private Object monitor = null;
      private static int i = 1;
      private static boolean first = true;
      private static boolean second = false;
      private static boolean third = false;
    
      public Notifier(Object objcurr) {
        this.monitor = objcurr;
      }
    
      @Override
      public void run() {
        try {
          while (true) {
            synchronized (monitor) {
              String Tname = Thread.currentThread().getName();
              if (first && Tname.equalsIgnoreCase("T1")) {
                print();
                first = false;
                second = true;
                monitor.notifyAll();
                monitor.wait();
              } else if (second && Tname.equalsIgnoreCase("T2")) {
                print();
                second = false;
                third = true;
                monitor.notifyAll();
                monitor.wait();
              } else if (third && Tname.equalsIgnoreCase("T3")) {
                print();
                third = false;
                first = true;
                monitor.notifyAll();
                monitor.wait();
              } else {
                monitor.wait();
              }
            }
            Thread.sleep(1000);
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    
      private void print() {
        System.out.println(Thread.currentThread().getName() + " - " + Notifier.i++);
      }
    
    0 讨论(0)
  • 2021-02-06 00:03
    package ThreadCoreConcepts;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * 3 Thread T1,T2,T3 will print output {1,2,3 4,5,6 7,8,9} Where T1 will print
     * {1,4,7} , T2 will print { 2,5,8} and T3 will print {3,6,9}
     * 
     * @author harsmahe
     *
     */
    public class ThreeThreadSequenceGen {
        private volatile static int value = 1;
    
        public static void main(String args[]) throws InterruptedException {
            ThreeThreadSequenceGen gen = new ThreeThreadSequenceGen();
            Object mutex = new Object();
            Thread t1 = new Thread(gen.new RunThread(1, mutex));
            t1.setName("1");
            Thread t2 = new Thread(gen.new RunThread(2, mutex));
            t2.setName("2");
            Thread t3 = new Thread(gen.new RunThread(3, mutex));
            t3.setName("3");
            t1.start();
            t2.start();
            t3.start();
    
        }
    
        class RunThread implements Runnable {
            private int start = 0;
            private Object mutex;
            private List<Integer> list = new ArrayList<Integer>();
    
            public RunThread(final int start, Object mutex) {
                // TODO Auto-generated constructor stub
                this.start = start;
                this.mutex = mutex;
            }
    
            @Override
            public void run() {
                try {
                    while (value <= 9) {
                        // while (true) {
                        // TODO Auto-generated method stub
                        int name = Integer.valueOf(Thread.currentThread().getName());
                        // System.out.println("[" + Thread.currentThread().getName()
                        // + "]");
                        // notifyAll();
    
                        synchronized (mutex) {
                            if (name == 1 && value == start) {
                                list.add(value);
                                System.out.println("[" + Thread.currentThread().getName() + "]" + value);
                                start = start + 3;
                                value++;
                                mutex.notifyAll();
                                mutex.wait();
                            } else if (name == 2 && value == start) {
                                System.out.println("[" + Thread.currentThread().getName() + "]" + value);
                                list.add(value);
                                start = start + 3;
                                value++;
                                mutex.notifyAll();
                                mutex.wait();
    
                            } else if (name == 3 && value == start) {
                                System.out.println("[" + Thread.currentThread().getName() + "]" + value);
                                list.add(value);
                                start = start + 3;
                                value++;
                                mutex.notifyAll();
                                if (value < 9) {
                                    mutex.wait();
                                }
    
                            } else {
                                mutex.notifyAll();
                                // mutex.wait();
                            }
                        }
    
                    }
    
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // System.out.println(list);
                }
    
            }
    
        }
    }
    
        enter code here
    
    0 讨论(0)
  • 2021-02-06 00:04
      public class TestClass {
    
        private volatile Integer count = 1;
        private volatile Integer threadIdToRun = 1;
        private Object object = new Object();
    
        public static void main(String[] args) {
    
            TestClass testClass = new TestClass();
            Thread t1 = new Thread(testClass.new Printer(1));
            Thread t2 = new Thread(testClass.new Printer(2));
            Thread t3 = new Thread(testClass.new Printer(3));
    
            t1.start();
            t2.start();
            t3.start();
        }
    
        class Printer implements Runnable {
    
            private int threadId;
    
            public Printer(int threadId) {
                super();
                this.threadId = threadId;
            }
    
            @Override
            public void run() {
                try {
                    while (count <= 20) {
                        synchronized (object) {
                            if (threadId != threadIdToRun) {
                                object.wait();
                            } else {
                                System.out.println("Thread " + threadId + " printed " + count);
                                count += 1;
    
                                if (threadId == 1)
                                    threadIdToRun = 2;
                                else if (threadId == 2)
                                    threadIdToRun = 3;
                                else if (threadId == 3)
                                    threadIdToRun = 1;
    
                                object.notifyAll();
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
            }
        }
    }
    

    Above program gives output

    Thread 1 printed 1
    Thread 2 printed 2
    Thread 3 printed 3
    Thread 1 printed 4
    Thread 2 printed 5
    Thread 3 printed 6
    Thread 1 printed 7
    Thread 2 printed 8
    Thread 3 printed 9
    Thread 1 printed 10
    Thread 2 printed 11
    Thread 3 printed 12
    Thread 1 printed 13
    Thread 2 printed 14
    Thread 3 printed 15
    Thread 1 printed 16
    Thread 2 printed 17
    Thread 3 printed 18
    Thread 1 printed 19
    Thread 2 printed 20
    
    0 讨论(0)
提交回复
热议问题