版权声明:be the one ~you will be the one~~ https://blog.csdn.net/Hqxcsdn/article/details/87895629
多线程-----------lock condirion reentrantlock reentrantreadwritelock
1.同步锁 :synchronized 修饰锁 ,在方法名前 加上 或者使用synchronized的对象锁
lock
2.lock 的wait 与 noyify
使用 condition
Condition cona =lock.newCondition();//同步监视器
public void sleepabya() {
lock.lock();
try{
System.out.println("i will do await by cona");
cona.await();
System.out.println("now i have get the signal! ");
}
catch(Exception e) {
}
finally {
lock.unlock();
}
}
public void notifyitbya() {//必须在condition.await()方法调用之前调用lock.lock()代码获得同步监视器,不然会报错。
lock.lock();
try{
System.out.println("i will signal it by a");
cona.signal();
System.out.println("ok, i do it from a");}
finally {
lock.unlock();
}
}
3.读写锁
reentrantreadwritelock
读读是共享的,但是 写写,读写 ,写读是互斥的
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
*
*/
/***
* @author 18071
* @Date 2019年2月23日
* 功能: 读写锁
***/
public class test {
public static void main(String args[]) {
service s =new service();
Thread a=new Thread(new threadA(s));
Thread b=new Thread(new threadB(s));
a.start();
try {
a.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
b.start();
}
}
class service{
ReentrantReadWriteLock rwlock=new ReentrantReadWriteLock();
public void read() {
rwlock.readLock().lock();
try {
System.out.println("我获取到了 read 锁 -by "+ Thread.currentThread().getName());
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
}
}
public void write() {
rwlock.writeLock().lock();
try {
System.out.println("我获取到了 write 锁 -by "+ Thread.currentThread().getName());
//Thread.sleep(1000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
}
}
}
class threadA implements Runnable {
private service s=new service();
threadA(service s){
this.s=s;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
// TODO Auto-generated method stub
s.read();
}
}
class threadB implements Runnable {
private service s=new service();
threadB(service s){
this.s=s;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
// TODO Auto-generated method stub
s.read();
}
}