package com.example.demo.juc;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class CountDownLatchDemo {
private static CountDownLatch countDownLatch = new CountDownLatch(2);
public static void main(String[] args) {
List<User> users = new ArrayList<>();
users.add(new User(10086L,"刘备",36));
users.add(new User(10087L,"张飞",32));
long start = System.currentTimeMillis();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
users.get(0).setName("线程一");
countDownLatch.countDown();
},String.valueOf(0)).start();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(users.get(1).getName());
users.get(1).setName("线程二 ");
countDownLatch.countDown();
},String.valueOf(1)).start();
//线程未达到CountDownLatch指定的数量,会阻塞
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println((System.currentTimeMillis()-start)/1000);
System.out.println(users);
}
}
@Data
@AllArgsConstructor
@ToString
class User{
private Long userId;
private String name;
private Integer age;
}
package com.example.demo.juc;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(2,()->{
System.out.println("人齐了一起出发");
});
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(5);
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(0)).start();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(3);
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(1)).start();
}
}
package com.example.demo.juc;
import java.util.Random;
import java.util.concurrent.Semaphore;
public class SemaphoreDemo {
//停车场同时容纳的车辆10
private static Semaphore semaphore=new Semaphore(400);
public static void main(String[] args) {
//模拟600辆车进入停车场
for(int i=0;i<600;i++){
new Thread(()->{
try {
System.out.println("===="+Thread.currentThread().getName()+"来到停车场");
if(semaphore.availablePermits()==0){
System.out.println("车位不足,请耐心等待");
}
//获取令牌尝试进入停车场
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"成功进入停车场");
//模拟车辆在停车场停留的时间,相当于业务方法对资源的使用
Thread.sleep(new Random().nextInt(10000));
System.out.println(Thread.currentThread().getName()+"驶出停车场");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//释放令牌,腾出停车场车位
semaphore.release();
}
}).start();
}
}
}