HTML/JavaScript小工具

HTML/JavaScript小工具

2013年5月2日 星期四

Java 進階 Lock - 1 lock()

Conditions

long awaitNanos(long nanosTimeout)
boolean await(long time, TimeUnit unit)
boolean awaitUntil(Date deadline)

 If
you want non-interruptible waiting, you can call awaitUninterruptibly().
signalAll()




import java.util.concurrent.locks.*;

class LockUnlock {
        public static void main(String []args) {
                Lock lock = new ReentrantLock();
                try {
                        System.out.print("Lock 1 ");
                        lock.lock();
                        System.out.print("Critical section 1 ");
                        System.out.print("Lock 2 ");
                        lock.lock();    // LOCK_2
                        System.out.print("Critical section 2 ");
                } finally {
                        lock.unlock();
                        System.out.print("Unlock 2 ");
                        lock.unlock();  // UNLOCK_1
                        System.out.print("Unlock 1 ");
                }
        }
}

In a re-entrant lock, you can acquire the same lock again. However, you need to release
that lock the same number of times.
可以獲得多次一樣的鎖,但記得要將他們依獲得的次數給予釋放!



ReentrantLock reent = new ReentrantLock();

reent.lock();

reent.unlock();
reent.unlock();
以上會產生Exception in thread "main" java.lang.IllegalMonitorStateException
因為生成一次lock但unlock了2次


lock()用法主要想取代過去synchronize 區塊 這種方式的鎖!!
synchronize(this){
}
synchronized有好有壞!!~~
lock 比起synchronized更靈活
 主要用法如下:

public class TTTT {
    public static void main(String[] args){

        Thread i1 = new Thread(new RunIt1());
        Thread i2 = new Thread(new RunIt2());
        i1.setPriority(Thread.MAX_PRIORITY);
        i1.setName("Thread1");
        i2.setName("Thread2");
        i1.start();
        i2.start();
     //   i1.interrupt();
    }

}

class TestX2{
 private static Lock lock1 = new ReentrantLock();
public static void addX() throws InterruptedException{
try{
System.out.println("Thread addX Name 1:"+Thread.currentThread().getName());
lock1.lock();//鎖定區塊
System.out.println("Thread  addX Name in lock block:"+Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(5);      

}finally{
lock1.unlock(); //解鎖
System.out.println("Thread addX Name 2 UNLock:"+Thread.currentThread().getName());
}
}

public  static void delX() throws InterruptedException{
try{
TimeUnit.SECONDS.sleep(1);
System.out.println("Thread Name delX 1:"+Thread.currentThread().getName());
lock1.lock();//鎖定區塊
System.out.println("Thread Name delX in lock block:"+Thread.currentThread().getName());
System.out.println("Thread Name delX 2:"+Thread.currentThread().getName());
}finally{
lock1.unlock();//解鎖

}
}
}

class RunIt1 implements Runnable{  
    public void run(){
        try{
        System.out.println("RunIt1....:Start");
        TestX2.addX();
        }
        catch (InterruptedException e){
            System.out.println(Thread.currentThread().getName() + " interrupted");
        }
    }
}

class RunIt2 implements Runnable{

@Override
public void run() {
System.out.println("RunIt2....:Start");
// TODO Auto-generated method stub
try {
TestX2.delX();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

主要方法用紅色區塊表示!!

此程式碼會印出


RunIt1....:Start
RunIt2....:Start
Thread addX Name 1:Thread1
Thread  addX Name in lock block:Thread1
此時Thread1開始睡!!!~~~於是開始進入Thread2
Thread Name delX 1:Thread2-->進入 Thread2但是因為有鎖所以沒法進到in lock block
Thread addX Name 2 UNLock:Thread1-->Thread1睡醒了解鎖
Thread Name delX in lock block:Thread2-->進入 Thread2的block



沒有留言:

張貼留言