ReentrantLock
ReentrantLock 该锁与 synchronized 的区别 synchronized是自动解锁 而ReentrantLock 是手动加锁解锁 lock.lock(); 加锁 lock.unlock();解锁
Lock lock = new ReentrantLock();
void m1() {
try {
lock.lock(); //加锁
for (int i = 0; i < 10; i++) {
TimeUnit.SECONDS.sleep(1);
System.out.println(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();//解锁
}
}
ReentrantLock 还具有尝试锁定功能 trylock trylock不管锁定与否都会继续执行 可以通过返回来判断是否已经锁定 也可以指定tryLock的时间
Lock lock = new ReentrantLock();
void a() {
/*
boolean locked = lock.tryLock(); //尝试锁定
System.out.println("m2 ..." + locked);
if(locked) lock.unlock(); //如果锁定就解锁
*/
boolean locked = false;
try {
locked = lock.tryLock(5, TimeUnit.SECONDS);//指定时间5秒没有竞争到就往下走
System.out.println("m2 ..." + locked);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if(locked) lock.unlock();
}
}
ReentrantLock lockInterruptibly 可以被打断的加锁 interrupt可以打断lockInterruptibly 竞争到了也会被打断 竞争不到会停止等待
Lock lock = new ReentrantLock(true); 此时是开启公平锁 公平锁定义自己查
public static void main(String[] args) {
Lock lock = new ReentrantLock();
//开启线程1一直执行
Thread t1 = new Thread(()->{
try {
lock.lock();
System.out.println("t1 start");
TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
System.out.println("t1 end");
} catch (InterruptedException e) {
System.out.println("interrupted!");
} finally {
lock.unlock();
}
});
t1.start();
//线程而竞争
Thread t2 = new Thread(()->{
try {
lock.lockInterruptibly(); //可以对interrupt()方法做出相应
System.out.println("t2 start");
TimeUnit.SECONDS.sleep(5);
System.out.println("t2 end");
} catch (InterruptedException e) {
System.out.println("interrupted!");
} finally {
lock.unlock();
}
});
t2.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
//此时可以打断线程2的等待使其结束竞争
t2.interrupt();
}
CountDownLatch
CountDownLatch latch = new CountDownLatch(5); 指定数量
latch.countDown(); 数量减一
latch.await(); 等待的点
latch.await();在某一个点卡住 然后当CountDownLatch指定数量走完之后再往下执行
在创建CountDownLatch的时候指定数量 比如 5 然后每次执行
latch.countDown()就会减一
当然如下所示join也可以实现 但是join是所有线程执行结束才会往下执行,不如CountDownLatch灵活 因为你可以再一个线程中多次countDown
public static void main(String[] args) {
usingJoin();
usingCountDownLatch();
}
private static void usingCountDownLatch() {
Thread[] threads = new Thread[100];
CountDownLatch latch = new CountDownLatch(threads.length);
for(int i=0; i<threads.length; i++) {
threads[i] = new Thread(()->{
int result = 0;
for(int j=0; j<10000; j++) result += j;
latch.countDown();
});
}
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end latch");
}
private static void usingJoin() {
Thread[] threads = new Thread[100];
for(int i=0; i<threads.length; i++) {
threads[i] = new Thread(()->{
int result = 0;
for(int j=0; j<10000; j++) result += j;
});
}
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
for (int i = 0; i < threads.length; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("end join");
}
CyclicBarrier
如下代码很 设置一个值10 当下方循环执行barrier.await();10次之后才会执行,意思就是每10次执行放开一次没啥可说的哈哈哈隔
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(10, () -> System.out.println("满了"));
for(int i=0; i<100; i++) {
new Thread(()->{
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
Phaser
如下所示 这个比较麻烦首先说代码大致逻辑
5个参加婚礼的人 外加新郎新娘两人
婚礼进程分为 到达 => 吃饭 => 离开 => 洞房
前三个是所有人 东方是新郎新娘两人
知识关键点
Phaser 类的onAdvance方法
只有所有人都执行之后才会调用
该方法共有两个参数 第一个参数当前阶段 第二个参数 执行中arriveAndAwaitAdvance的数量 arriveAndDeregister不计入第二个参数数量phaser.register()这个方法也可以往上加
该方法返回true代表成功
大致执行过程创建一个类继承Phaser 然后创建实例
然后往里面家线程new Thread(new Person(“p” + i)).start();
下面逻辑自己看写不下去了哈哈哈隔
static Random r = new Random();
static MarriagePhaser phaser = new MarriagePhaser();
static void milliSleep(int milli) {
try {
TimeUnit.MILLISECONDS.sleep(milli);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
phaser.bulkRegister(7);
for(int i=0; i<5; i++) {
new Thread(new Person("p" + i)).start();
}
new Thread(new Person("新郎")).start();
new Thread(new Person("新娘")).start();
}
static class MarriagePhaser extends Phaser {
@Override
protected boolean onAdvance(int phase, int registeredParties) {
switch (phase) {
case 0:
System.out.println("所有人都到齐了!" + registeredParties);
System.out.println();
return false;
case 1:
System.out.println("所有人都吃完了!" + registeredParties);
System.out.println();
return false;
case 2:
System.out.println("所有人都离开了!" + registeredParties);
System.out.println();
return false;
case 3:
System.out.println("婚礼结束!新郎新娘抱抱!" + registeredParties);
return true;
default:
return true;
}
}
}
static class Person implements Runnable {
String name;
public Person(String name) {
this.name = name;
}
public void arrive() {
milliSleep(r.nextInt(1000));
System.out.printf("%s 到达现场!\n", name);
phaser.arriveAndAwaitAdvance();
}
public void eat() {
milliSleep(r.nextInt(1000));
System.out.printf("%s 吃完!\n", name);
phaser.arriveAndAwaitAdvance();
}
public void leave() {
milliSleep(r.nextInt(1000));
System.out.printf("%s 离开!\n", name);
phaser.arriveAndAwaitAdvance();
}
private void hug() {
if(name.equals("新郎") || name.equals("新娘")) {
milliSleep(r.nextInt(1000));
System.out.printf("%s 洞房!\n", name);
phaser.arriveAndAwaitAdvance();
} else {
phaser.arriveAndDeregister();
//phaser.register()
}
}
@Override
public void run() {
arrive();
eat();
leave();
hug();
}
}
ReadWriteLock
读写锁 故名思意的东西
读写锁的概念其实就是共享锁和排他锁,读锁就是共享锁,写锁就是排他锁read()读一个数据,write()写一个数据
ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); 读写锁
readWriteLock.readLock(); 读锁
readWriteLock.writeLock(); 写锁
static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
static Lock readLock = readWriteLock.readLock();
static Lock writeLock = readWriteLock.writeLock();
public static void read(Lock lock) {
try {
lock.lock();
Thread.sleep(1000);
System.out.println("read over!");
//模拟读取操作
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void write(Lock lock, int v) {
try {
lock.lock();
Thread.sleep(1000);
value = v;
System.out.println("write over!");
//模拟写操作
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
Runnable readR = ()-> read(readLock); //读操作
Runnable writeR = ()->write(writeLock, new Random().nextInt()); //写操作
for(int i=0; i<18; i++) new Thread(readR).start();
for(int i=0; i<2; i++) new Thread(writeR).start();
}
Semaphore
做限流用的 Semaphore s = new Semaphore(2, true); 最多限制2个 第二个参数true就是公平锁
几个关键方法
s.acquire() 阻塞方法获取 执行的时候 会减一如上 参数是2 执行一次则会减一 当减少到0的时候 再来一个线程获取不到了会阻塞
release()方法当你用acquire()方法后执行完了执行release将会还原也就是数值加一 懂得都懂啊
public static void main(String[] args) {
//Semaphore s = new Semaphore(2);
Semaphore s = new Semaphore(2, true);
//允许一个线程同时执行
//Semaphore s = new Semaphore(1);
new Thread(()->{
try {
s.acquire();
System.out.println("T1 running...");
Thread.sleep(200);
System.out.println("T1 running...");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
s.release();
}
}).start();
new Thread(()->{
try {
s.acquire();
System.out.println("T2 running...");
Thread.sleep(200);
System.out.println("T2 running...");
s.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
Exchanger
Exchanger叫做交换器,俩人之间互相交换个数据用的。怎么交换呢,看这里,我第一个线程有一个成员变量叫s,然后exchanger.exchange(s),第二个也是这样,t1线程名字叫T1,第二个线程名字叫T2。到最后,打印出来你会发现他们俩交换了一下。线程间通信的方式非常多,这只是其中一种,就是线程之间交换数据用的。
static Exchanger<String> exchanger = new Exchanger<>();
public static void main(String[] args) {
new Thread(()->{
String s = "T1";
try {
s = exchanger.exchange(s);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " " + s);
}, "t1").start();
new Thread(()->{
String s = "T2";
try {
s = exchanger.exchange(s);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " " + s);
}, "t2").start();
}