点我跳转至JUC并发编程总结(二)
System.out.println(Runtime.getRuntime().availableProcessors());
public enum State {
NEW,
RUNNABLE,
BLOCKED,
WAITING,//等待
TIMED_WAITING,//等待超时
TERMINATED;//终止
}
TimeUnit.SECONDS.sleep(5);
class Data {
private int num = 0;
public synchronized void increment() throws InterruptedException {
while (num != 0) { //防止虚假唤醒问题
this.wait();
}
num++;
System.out.println("生产了一个:" + num);
this.notifyAll();
}
public synchronized void decrement() throws InterruptedException {
while (num == 0) {
this.wait();
}
num--;
System.out.println("消费了一个:" + num);
this.notifyAll();
}
public static void main(String[] args) {
System.out.println(Runtime.getRuntime().availableProcessors());
Data data = new Data();
new Thread(() -> {
data.increment();
}).start();
new Thread(() -> {
data.decrement();
}).start();
}
}
class Data2 {
private int num = 0;
Lock lock =new ReentrantLock();
Condition condition= lock.newCondition();
public void increment() {
try {
lock.lock(); //业务代码写在try里,这是模板
while (num != 0) { //防止虚假唤醒问题
condition.await();
}
num++;
System.out.println("生产了一个:" + num);
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void decrement() {
lock.lock();
try {
while (num == 0) {
condition.await();
}
num--;
System.out.println("消费了一个:" + num);
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
public class Demo {
public static void add(List<Integer> a,Integer b){
a.add(b);
}
public static void main(String[] args) throws InterruptedException {
List<Integer> a=new LinkedList<>();
ReentrantLock lock=new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
AtomicInteger num= new AtomicInteger(1);
Thread t1= new Thread(()->{
for (int i=0;i<100;i++){
lock.lock();
try {
while (num.get() !=1){
condition1.await();
}
if (i%2==0){
add(a,i);
num.set(2);
}
condition2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
});
Thread t2= new Thread(()->{
for (int i=0;i<100;i++){
lock.lock();
try {
while (num.get()!=2){
condition2.await();
}
if (i%2!=0){
add(a,i);
num.set(1);
}
condition1.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(a);
}
}
ConcurrentModificationException
List<String> list =new Vector<>();
List<String> list2 = Collections.synchronizedList(new ArrayList<>());
List<String> list3 =new CopyOnWriteArrayList<>();
Set<String> set =Collections.synchronizedSet(new HashSet<>());
Set<String> set2 =new CopyOnWriteArraySet<>();
ConcurrentHashMap<String,String> map=new ConcurrentHashMap<>();
public class Demo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyThread thread =new MyThread();
FutureTask ft=new FutureTask(thread);
new Thread(ft,"A00").start();
String result= (String) ft.get();
FutureTask ft2=new FutureTask(new MyThread());
new Thread(ft2,"A01").start();
String result2= (String) ft.get();
}
}
class MyThread implements Callable<String>{
@Override
public String call() throws Exception {
return "返回泛型接口的String类";
}
}
public class Demo03 {
public static void main(String[] args) throws InterruptedException {
CountDownLatch cdl=new CountDownLatch(5); //倒计时为5
for (int i = 0; i <10 ; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"线程执行完成");
cdl.countDown();
}).start();
}
cdl.await();
System.out.println("exit");
}
}
CyclicBarrier cb=new CyclicBarrier(5,()->{
System.out.println("五个县城全部执行完成!");
//会执行2次,可以设置执行定期任务。
});
for (int i = 0; i <10 ; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"线程执行完成");
cb.await(); //try..catch
}).start();
}
public class StudySemaphore {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
//信号量,只允许 3个线程同时访问
Semaphore semaphore = new Semaphore(3);
for (int i=0;i<10;i++){
final long num = i;
executorService.submit(new Runnable() {
@Override
public void run() {
try {
//获取许可
semaphore.acquire();
//执行
System.out.println("Accessing: " + num);
Thread.sleep(new Random().nextInt(5000)); // 模拟随机执行时长
//释放
semaphore.release();
System.out.println("Release..." + num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
executorService.shutdown();
}
}
ReadWriteLock
同Lock
一样也是一个接口,提供了readLock
和writeLock
两种锁的操作机制,一个是只读的锁,一个是写锁。 SynchronousQueue<String> blockingDeque= new SynchronousQueue<String>();
new Thread(()->{
blockingDeque.put("1"); //try...catch
blockingDeque.put("2");
blockingDeque.put("3");
},"生产者").start();
new Thread(()->{
System.out.println("消费了:"+blockingDeque.take());
System.out.println("消费了:"+blockingDeque.take());
System.out.println("消费了:"+blockingDeque.take());
},"消费者").start();
ExecutorService tp1= Executors.newSingleThreadExecutor(); //单个线程
ExecutorService tp2= Executors.newFixedThreadPool(5); //创建线程池大小
ExecutorService tp3= Executors.newCachedThreadPool(); //遇强则强,遇弱则弱
for (int i = 0; i <50 ; i++) {
tp1.execute(()->{
System.out.println(Thread.currentThread().getName()+"ok");
});
}
ThreadPoolExecutor
构造方法,可以看到这七大参数。 public ThreadPoolExecutor(int corePoolSize, //核心线程数
int maximumPoolSize, //最大线程数
long keepAliveTime, //空闲等待时间
TimeUnit unit, //空闲等待时间单位
BlockingQueue<Runnable> workQueue, //工作队列
ThreadFactory threadFactory, //使用的工程,
RejectedExecutionHandler handler //队列满了的时候拒绝策略。
) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
new ThreadPoolExecutor.AbortPolicy(); //队列满了,抛出异常
new ThreadPoolExecutor.CallerRunsPolicy(); //哪来回哪去,一般丢给主线程
new ThreadPoolExecutor.DiscardOldestPolicy(); //丢列满了丢掉任务,不抛出异常
new ThreadPoolExecutor.DiscardPolicy(); //队列满了,尝试和最早的竞争资源
ExecutorService pool=new ThreadPoolExecutor(3,
5,
3, TimeUnit.SECONDS,
new LinkedBlockingDeque<>(),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
for (int i = 0; i <50 ; i++) {
int finalI = i;
pool.execute(new Thread(()->{
System.out.println(Thread.currentThread().getName()+"------"+ finalI);
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}));
}