3 Threads Printing numbers in sequence

前端 未结 14 1312
不思量自难忘°
不思量自难忘° 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: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();
       }
    }
    

提交回复
热议问题