多執行緒程式碼示例

劍握在手發表於2013-11-13
 1 package test.synchornize;
 2 
 3 import java.util.concurrent.locks.*;
 4 
 5 class runab implements Runnable{
 6     boolean x = true;
 7     static Lock lock = new ReentrantLock();
 8     static Condition con1 = lock.newCondition();
 9     static Condition con2 = lock.newCondition();
10     runab(boolean x){
11         this.x = x;
12     }
13     public void run() {
14         lock.lock();
15         try {
16             System.out.println("Start---" + Thread.currentThread().getName());
17             if(x) {
18                 x = false;
19                 //try {con1.await();con2.await();} catch (InterruptedException e) {}
20                 try {con1.await();} catch (InterruptedException e) {}
21             }
22             System.out.println("End---" + Thread.currentThread().getName());
23         } finally {
24 
25             //con2.signalAll();
26             con1.signalAll();
27             lock.unlock();
28         }
29     }
30 }
31 
32 public class showLock {
33 
34     public static void main(String[] args) {
35         runab rab = new runab(true);
36         runab rab1 = new runab(false);
37         Thread th = new Thread(rab);
38         Thread th1 = new Thread(rab1);
39         th.start();
40         try {
41             Thread.sleep(100);
42         } catch (InterruptedException e) {
43             // TODO Auto-generated catch block
44             e.printStackTrace();
45         }
46         th1.start();
47         
48     }
49 
50 }

 

相關文章