1.按顺序打印ABC

三个线程,每个线程分别打印A,B,C各十次,现在要求按顺序输出A,B,C

package concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class 按顺序打印ABC { public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(3);
Object lockA = new Object();
Object lockB = new Object();
Object lockC = new Object();
Runnable rA = new OrderPrintABC(lockC, lockA, "A");
Runnable rB = new OrderPrintABC(lockA, lockB, "B");
Runnable rC = new OrderPrintABC(lockB, lockC, "C");
threadPool.execute(rA);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadPool.execute(rB);
threadPool.execute(rC);
threadPool.shutdown();
} private static class OrderPrintABC implements Runnable{ private Object preLock;
private Object selfLock;
private String taskName;
private int count = 10; public OrderPrintABC(Object preLock, Object selfLock, String taskName) {
this.preLock = preLock;
this.selfLock = selfLock;
this.taskName = taskName;
} @Override
public void run() {
while(count > 0) {
synchronized(preLock) {
synchronized(selfLock) {
System.out.print(taskName);
count--;
selfLock.notifyAll();
}
if(count > 0) {
try {
preLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}

2. 生产者消费者: 要尽量使用BlockingQueue来实现

https://github.com/CyC2018/CS-Notes/blob/master/notes/Java%20%E5%B9%B6%E5%8F%91.md#blockingqueue

package concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; public class 生产者消费者 { //有界队列
private static class BoundQueue<T> {
private Object[] items;
private int count = 0;
private Lock lock = new ReentrantLock();
private Condition notEmpty = lock.newCondition();
private Condition notFull = lock.newCondition(); public BoundQueue(int size) {
items = new Object[size];
} public void add(T t) throws InterruptedException {
lock.lock();
try {
Long nano = 0L;
while (count == items.length) {
if(nano < 0L) {
return;
};
System.out.println("仓库已满");
notFull.awaitNanos(5000);
}
items[count++] = t;
System.out.println("生产者放入" + t);
notEmpty.signal();
Thread.sleep(1000);
} finally {
lock.unlock();
}
} public T remove() throws InterruptedException {
lock.lock();
T t;
try {
Long nano = 0L;
while (count == 0) {
if(nano < 0L) {
return null;
};
System.out.println("仓库已空");
nano = notEmpty.awaitNanos(5000);
}
t = (T) items[count - 1];
items[--count] = null;
System.out.println("消费者接收" + t);
notFull.signal();
Thread.sleep(1000);
} finally {
lock.unlock();
}
return t;
}
} //生产者
private static class Product implements Runnable{
private BoundQueue queue;
private int count; public Product (BoundQueue queue, int count) {
this.queue = queue;
this.count = count;
} public void run() {
int itr = 1;
while(itr <= count) {
try {
queue.add(itr);
itr++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} //消费者
private static class Consumer implements Runnable{
private BoundQueue queue;
private int count; public Consumer(BoundQueue queue, int count) {
this.queue = queue;
this.count = count;
} @Override
public void run() {
int itr = 0;
while(itr <= count) {
try {
queue.remove();
itr++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} public static void main(String[] args) {
BoundQueue<Integer> queue = new BoundQueue<>(5);
int count = 6;
Runnable rP = new Product(queue, count);
Runnable rC = new Consumer(queue, count);
ExecutorService threadPool = Executors.newFixedThreadPool(2);
threadPool.execute(rP);
threadPool.execute(rC);
threadPool.shutdown();
}
}

https://github.com/CyC2018/CS-Notes/blob/master/notes/Java%20%E5%B9%B6%E5%8F%91.md#blockingqueue

Java并发练习的更多相关文章

  1. 多线程的通信和同步(Java并发编程的艺术--笔记)

    1. 线程间的通信机制 线程之间通信机制有两种: 共享内存.消息传递.   2. Java并发 Java的并发采用的是共享内存模型,Java线程之间的通信总是隐式执行,通信的过程对于程序员来说是完全透 ...

  2. 【Java并发编程实战】----- AQS(四):CLH同步队列

    在[Java并发编程实战]-–"J.U.C":CLH队列锁提过,AQS里面的CLH队列是CLH同步锁的一种变形.其主要从两方面进行了改造:节点的结构与节点等待机制.在结构上引入了头 ...

  3. 【Java并发编程实战】----- AQS(三):阻塞、唤醒:LockSupport

    在上篇博客([Java并发编程实战]----- AQS(二):获取锁.释放锁)中提到,当一个线程加入到CLH队列中时,如果不是头节点是需要判断该节点是否需要挂起:在释放锁后,需要唤醒该线程的继任节点 ...

  4. 【Java并发编程实战】----- AQS(二):获取锁、释放锁

    上篇博客稍微介绍了一下AQS,下面我们来关注下AQS的所获取和锁释放. AQS锁获取 AQS包含如下几个方法: acquire(int arg):以独占模式获取对象,忽略中断. acquireInte ...

  5. 【Java并发编程实战】-----“J.U.C”:CLH队列锁

    在前面介绍的几篇博客中总是提到CLH队列,在AQS中CLH队列是维护一组线程的严格按照FIFO的队列.他能够确保无饥饿,严格的先来先服务的公平性.下图是CLH队列节点的示意图: 在CLH队列的节点QN ...

  6. 【Java并发编程实战】-----“J.U.C”:CountDownlatch

    上篇博文([Java并发编程实战]-----"J.U.C":CyclicBarrier)LZ介绍了CyclicBarrier.CyclicBarrier所描述的是"允许一 ...

  7. 【Java并发编程实战】-----“J.U.C”:CyclicBarrier

    在上篇博客([Java并发编程实战]-----"J.U.C":Semaphore)中,LZ介绍了Semaphore,下面LZ介绍CyclicBarrier.在JDK API中是这么 ...

  8. 【Java并发编程实战】-----“J.U.C”:ReentrantReadWriteLock

    ReentrantLock实现了标准的互斥操作,也就是说在某一时刻只有有一个线程持有锁.ReentrantLock采用这种独占的保守锁直接,在一定程度上减低了吞吐量.在这种情况下任何的"读/ ...

  9. Java并发编程:volatile关键字解析

    Java并发编程:volatile关键字解析 volatile这个关键字可能很多朋友都听说过,或许也都用过.在Java 5之前,它是一个备受争议的关键字,因为在程序中使用它往往会导致出人意料的结果.在 ...

  10. JAVA并发编程J.U.C学习总结

    前言 学习了一段时间J.U.C,打算做个小结,个人感觉总结还是非常重要,要不然总感觉知识点零零散散的. 有错误也欢迎指正,大家共同进步: 另外,转载请注明链接,写篇文章不容易啊,http://www. ...

随机推荐

  1. 记 CentOS 服务器上安装 neo4j 图数据库及本地访问

    下载 去官网下载压缩包放到服务器上.地址为neo4j 下载中心,我这里选择的是 Neo4j 3.5.25 (tar).具体如何做呢?我这里使用的是土方法,即先压缩包下载到本地电脑(win 10系统), ...

  2. 本地项目上传至GitHub

    本地项目上传至GitHub 使用git上传 一.安装git 直接官网下载,安装即可. git官网下载 github下载 按照好后大概就是这个样子 二.创建公钥和私钥 有的就可跳过此步骤 我们双击打开g ...

  3. Java基础经典案例

    案例列表 01减肥计划switch版本 02减肥计划if版本 03逢七跳过 04不死神兔 05百钱白鸡 06数组元素求和 07判断两个数组是否相同 08查找元素在数组中的索引 09数组元素反转 10评 ...

  4. ES6模板字符串及字符串的扩展方法

    一.ES6模板字符串 传统定义字符串的方式是: const str='hello es2015,this is a string' ES6新增了一种定义字符串的方式用反引号进行标识 const str ...

  5. 2018年第九届蓝桥杯B组(201806-----递增三元组)

    给定三个整数数组 A = [A1, A2, - AN], B = [B1, B2, - BN], C = [C1, C2, - CN], 请你统计有多少个三元组(i, j, k) 满足: 1 < ...

  6. Lesson_strange_words2

    cap 大写字母 mechanical 机械的,力学的 optical 光学的,视觉的 charge 电荷,负载 couple 耦合的,联接的,成对的 charge-coupled device 电荷 ...

  7. ContactCollections Design Report

    通讯录的设计采用了分层+接口+面向对象+文件操作+方法实现 分三层实现,共使用了四个包,实现业务数据访问和界面的分离     contactaccess包实现对文件的访问         包括数据访问 ...

  8. 【Flutter】容器类组件之Container容器

    前言 Container是一个组合类容器,它本身不对应具体的RenderObject,它是DecoratedBox.ConstrainedBox.Transform.Padding.Align等组件组 ...

  9. Azure Key Valut 简介

    Azure Key Vault(密钥库)是用于安全地存储和访问Secret的云服务,Secret是需要严格控制访问权限的内容,例如API密钥,密码,证书或加密密钥.Key Vault Service支 ...

  10. 【MYSQL】MySQL5.6.37二进制安装

    最近有个项目要用到mysql 于是在mysql的论坛中找到了一个5.6.37版本的 下面介绍怎么安装和使用mysql 下载地址: https://dev.mysql.com/downloads/mys ...