2016-06-09-Onsite

/*第一题: 多线程题, 打印 
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)