package cn.edu.sysu; import java.util.ArrayList; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class ObjectQueue{ private final int size=10; private final Semaphore notEmpty=new Semaphore(0); private final Semaphore notFull=new Semaphore(size); private ArrayList<Integer> ints=new ArrayList<Integer>(); private Lock lock=new ReentrantLock(); public ObjectQueue(){} public void putItem(Integer i){ try { notFull.acquire(); lock.lock(); ints.add(i); notEmpty.release(); } catch (Exception e) { System.out.println("Exception happened in object queue put item"); } finally{ lock.unlock(); } } public Integer getItem(){ try { notEmpty.acquire(); lock.lock(); Integer i=ints.remove(0); notFull.release(); return i; } catch (Exception e) { System.out.println("Exception happened in object queue get item"); } finally{ lock.unlock(); } return null; } } class Producer extends Thread{ int id; ObjectQueue queue; public Producer(int i, ObjectQueue q){ super(); this.id=i; this.queue=q; } public void run() { for(int i=0;i<100;i++){ queue.putItem(new Integer(i+10000)); System.out.println("Producer "+id+" produce Integer "+(i+10000)); try { Thread.currentThread().sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class Consumer extends Thread{ int id; ObjectQueue queue; public Consumer(int i, ObjectQueue q){ super(); this.id=i; this.queue=q; } public void run() { for(int i=0;i<100;i++){ Integer item=queue.getItem(); System.out.println("Consumer "+id+" consume Integer "+item.intValue()); try { Thread.currentThread().sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public class LockImplmentation { /** * @param args */ public static void main(String[] args) { ObjectQueue queue=new ObjectQueue(); Producer p=new Producer(1,queue ); int consumerCount=5; Consumer c[]=new Consumer[consumerCount]; for(int i=0;i<consumerCount;i++){ c[i]=new Consumer(i, queue); c[i].start(); } p.start(); } }
要把心靜下來的話仍是應該去寫一些基本的程序,雖然很簡單,可是不失爲筆試面試的有效材料,有點不規範的地方,可是我就是喜歡extends Thread,用Runnable的話好像仍是不習慣多寫幾行。另外的話能夠複習一下進程同步的知識 java
連什麼是可重入鎖都不知道就在那裏瞎寫:
面試
可重入鎖,最關鍵的地方是認識他 app
final Condition con = lock.newCondition(); ui
以後所獲得的condition調用await,和直接調用Thread.sleep的區別 this
前者是lock住了可是不保持這個鎖(別人能夠保持這個鎖,到他回來的時候,就是重入了),後者不光是保持了這個鎖,並且lock了這個鎖(別人怎麼也進不來了) spa
看這裏:http://tenyears.iteye.com/blog/48750 線程
官方: code
若是該鎖定沒有被另外一個線程保持,則獲取該鎖定並當即返回,將鎖定的保持計數設置爲 1。
若是當前線程已經保持該鎖定,則將保持計數加 1,而且該方法當即返回。
若是該鎖定被另外一個線程保持,則出於線程調度的目的,禁用當前線程,而且在得到鎖定以前,該線程將一直處於休眠狀態,此時鎖定保持計數被設置爲 1。
blog