015.1 Lock接口
内容:Lock接口使用步骤,同步生产大白兔奶糖的例子
同步代码块的锁是隐式的,显式容易让我们理解。所以我们使用这个显式的方法,方便理解代码。
######实现同步步骤:
1、获取锁:lock()
2、同步代码
3、释放锁:unlock()
但是同步代码可能出现异常,所以需要使用try{}finally{}
例子代码:
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class NewProducerConsumer { public static void main(String[] args) { Res r = new Res(); Producer producer = new Producer(r); Consumer consumer = new Consumer(r); Thread t0 = new Thread(producer); Thread t1 = new Thread(producer); Thread t2 = new Thread(consumer); Thread t3 = new Thread(consumer); t0.start(); t1.start(); t2.start(); t3.start(); } } class Res{ private String name; private int count; private boolean flag = false; Lock lock = new ReentrantLock(); //产生一个锁 public void set(String name) //Res的set方法和get方法是用的是同一个锁,所以同一个对象两个方法只会执行一个方法 { lock.lock(); //获取锁 try{ while(flag){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.name = name + "--" + count; count++; System.out.println(Thread.currentThread().getName()+"____生产者______"+this.name); flag = true; notifyAll(); } finally{ lock.unlock(); //释放锁 } } public void get() { lock.lock(); try{ while(!flag){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+"....消费者。。。。"+this.name); flag = false; notifyAll(); } finally{ lock.unlock(); } } } class Producer implements Runnable{ private Res r; public Producer(Res r) { this.r = r; } public void run() { int i = 0; while(i<100){ r.set("大白兔奶糖"); i++; } } } class Consumer implements Runnable{ private Res r; public Consumer(Res r) { this.r = r; } public void run() { int i = 0; while(i<100){ r.get(); i++; } } }
如果看不懂例子,欢迎提问