线程之间的通信
一、常见的锁的概念(需要了解在什么场景下使用)
1.公平锁和非公平锁
2.独占锁和非共享锁
3.乐观锁和悲观锁
4.重入锁
5.自旋锁
6.读写锁
二、读写锁
1.写锁重入的状态 (低16位保存写锁的个数)
2.读锁的个数 (高16位保存读锁的个数)
3.每个读锁重入的状态
三、Condition(指定叫醒某个线程) 的使用以及说明啊
1.方法await()、singal()
2.
四、join线程通信
五、ThreadLocal的使用
六、CountDownLatch(只有到0的时候才会释放锁)
七、CyclcBarrier()
八、Semaphore
acquire()、release()
九、FutureTask
Callable、Future(可以获得线程的结果)、FutureTask
十、HashMap(扩容时候线程不安全,容易出现死循环)、ConcurrentHashMap(线程是安全的)
HashMap key和Value可以为空、线程不安全
ConcurrentHashMap key和value不可以为空、线程安全
当一定长度超过8时候,有链表(O(N))变为红黑树(O(N*logN)),时间复杂度大大提升
package com.example.lib;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedLongSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
public class MyLock implements Lock {
private Help help = new Help();
@Override
public void lock() {
help.acquire(1);
}
@Override
public void lockInterruptibly() throws InterruptedException {
help.acquireInterruptibly(1);
}
@Override
public boolean tryLock() {
return help.tryAcquire(1);
}
@Override
public boolean tryLock(long l, TimeUnit timeUnit) throws InterruptedException {
return help.tryAcquireNanos(1,timeUnit.toNanos(l));
}
@Override
public void unlock() {
help.release(1);
}
@Override
public Condition newCondition() {
return help.newCondition() ;
}
private class Help extends AbstractQueuedLongSynchronizer{
@Override
protected boolean tryAcquire(long l) {
//第一个线程进来,可以拿到锁,因此我们可以返回true
//如果第二个线程进来,拿不到锁,返回false
//如果当前进来的线程和当前保存的线程是同一个线程,则可以拿到锁的
//如何判断是第一个线程还是其他线程
long state = getState();
Thread thread = Thread.currentThread();
if(state == 0){
if(compareAndSetState(0, l)){
setExclusiveOwnerThread(thread);
return true;
}
}else if (getExclusiveOwnerThread() == thread){
setState(state+1);
return true;
}
return false;
}
@Override
protected boolean tryRelease(long l) {
//锁的获取和释放一一对应的,调用该线程一定是当前线程
if(Thread.currentThread() != getExclusiveOwnerThread()){
return false;
}
long state = getState() - l;
boolean flag = false;
if(state == 0){
setExclusiveOwnerThread(null);
flag = true;
}
setState(state);
return flag;
}
Condition newCondition(){
return new ConditionObject();
}
}
}
package com.example.lib;
public class MyClass {
private int value = 0;
private MyLock lock = new MyLock();
public void a(){
lock.lock();
System.out.println("a");
b();
lock.unlock();
}
public void b(){
lock.lock();
System.out.println("b");
lock.unlock();
}
public int next(){
lock.lock();
try {
Thread.sleep(300);
return value++;
} catch (InterruptedException e) {
throw new RuntimeException();
}finally {
lock.unlock();
}
}
public static void main(String[] args){
final MyClass myClass = new MyClass();
new Thread(new Runnable() {
@Override
public void run() {
while (true){
myClass.a();
//System.out.println(Thread.currentThread().getId()
//+ "-" + myClass.next());
}
}
}).start();
}
}
posted on 2019-09-26 23:35 zhang11111wei 阅读(146) 评论(0) 编辑 收藏 举报