2016-06-09-Onsite

作者: 番茄晓蛋 | 来源:发表于2016-06-10 14:55 被阅读19次
    /*第一题: 多线程题, 打印 
    T1:1
    T2:2
    T3:3
    T1:4
    T2:5
    T3:6
    ….
    */
    
    // MultiThreadDemo.java
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class MultiThreadDemo extends Thread {
     int val;
     private Lock lock;
    
     public MultiThreadDemo(int i) {
      val = i;
      lock = new ReentrantLock();
     }
    
     public void run() {
      lock.lock();
       
       while (val < 100) { 
       int name = val % 3 == 0 ? 3 : val % 3;
       System.out.println("T" + name + " : " + val++);
      }
      lock.unlock();
    
     }
    
    }
    
    
    // MultiThreadDemoTest.java
    public class MultiThreadDemoTest {
    
     public static void main(String[] args) throws InterruptedException {
      // TODO Auto-generated method stub
      int val = 1;
      MultiThreadDemo t1 = new MultiThreadDemo(val);
      val++;
      MultiThreadDemo t2 = new MultiThreadDemo(val);
      val++;
      MultiThreadDemo t3 = new MultiThreadDemo(val);
      val++;
    
      t1.start();
      t1.join();
      t2.start();
      t2.join();
      t3.start();
      t3.join();
    
     }
    
    }
    

    相关文章

      网友评论

        本文标题:2016-06-09-Onsite

        本文链接:https://www.haomeiwen.com/subject/lcysdttx.html