Java并发练习
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并发练习的更多相关文章
- 多线程的通信和同步(Java并发编程的艺术--笔记)
1. 线程间的通信机制 线程之间通信机制有两种: 共享内存.消息传递. 2. Java并发 Java的并发采用的是共享内存模型,Java线程之间的通信总是隐式执行,通信的过程对于程序员来说是完全透 ...
- 【Java并发编程实战】----- AQS(四):CLH同步队列
在[Java并发编程实战]-–"J.U.C":CLH队列锁提过,AQS里面的CLH队列是CLH同步锁的一种变形.其主要从两方面进行了改造:节点的结构与节点等待机制.在结构上引入了头 ...
- 【Java并发编程实战】----- AQS(三):阻塞、唤醒:LockSupport
在上篇博客([Java并发编程实战]----- AQS(二):获取锁.释放锁)中提到,当一个线程加入到CLH队列中时,如果不是头节点是需要判断该节点是否需要挂起:在释放锁后,需要唤醒该线程的继任节点 ...
- 【Java并发编程实战】----- AQS(二):获取锁、释放锁
上篇博客稍微介绍了一下AQS,下面我们来关注下AQS的所获取和锁释放. AQS锁获取 AQS包含如下几个方法: acquire(int arg):以独占模式获取对象,忽略中断. acquireInte ...
- 【Java并发编程实战】-----“J.U.C”:CLH队列锁
在前面介绍的几篇博客中总是提到CLH队列,在AQS中CLH队列是维护一组线程的严格按照FIFO的队列.他能够确保无饥饿,严格的先来先服务的公平性.下图是CLH队列节点的示意图: 在CLH队列的节点QN ...
- 【Java并发编程实战】-----“J.U.C”:CountDownlatch
上篇博文([Java并发编程实战]-----"J.U.C":CyclicBarrier)LZ介绍了CyclicBarrier.CyclicBarrier所描述的是"允许一 ...
- 【Java并发编程实战】-----“J.U.C”:CyclicBarrier
在上篇博客([Java并发编程实战]-----"J.U.C":Semaphore)中,LZ介绍了Semaphore,下面LZ介绍CyclicBarrier.在JDK API中是这么 ...
- 【Java并发编程实战】-----“J.U.C”:ReentrantReadWriteLock
ReentrantLock实现了标准的互斥操作,也就是说在某一时刻只有有一个线程持有锁.ReentrantLock采用这种独占的保守锁直接,在一定程度上减低了吞吐量.在这种情况下任何的"读/ ...
- Java并发编程:volatile关键字解析
Java并发编程:volatile关键字解析 volatile这个关键字可能很多朋友都听说过,或许也都用过.在Java 5之前,它是一个备受争议的关键字,因为在程序中使用它往往会导致出人意料的结果.在 ...
- JAVA并发编程J.U.C学习总结
前言 学习了一段时间J.U.C,打算做个小结,个人感觉总结还是非常重要,要不然总感觉知识点零零散散的. 有错误也欢迎指正,大家共同进步: 另外,转载请注明链接,写篇文章不容易啊,http://www. ...
随机推荐
- IDEA 远程debug
远程debug tomcat 的Catalina.sh 里面有个参数 JPDA_ADDRESS="5555",默认为5555.启动tomcat时,用 ./catalina.sh j ...
- [leetcode349]Intersection of Two Arrays
设计的很烂的一道题 List<Integer> res = new ArrayList<>(); // int l1 = nums1.length; // int l2 = n ...
- Typecho 主题更换
Typecho 主题更换 前言 上一篇已经搭建自己的 Typecho 博客,博客搭建完成自带一个默认主题,不是很喜欢默认的主题,想换一个自己喜欢的主题,并在基础上进行修改. 本文就介绍下如何更换和自定 ...
- 学习笔记之Python人机交互小项目二:名片管理系统
继上次利用列表相关知识做了简单的人机交互的小项目名字管理系统后,当学习到字典时,老师又让我们结合列表和字典的知识,结合一起做一个名片管理系统,这里分享给在学习Python的伙伴! 1.不使用函数 1 ...
- 添加/删除/读写c盘文件——c#
一.前言: 有时候我们为自己的程序添加配置文件,如tet.ini.xml等文件,又或者保存软件运行时的日志 当我们把软件打包后,默认安装在c盘,而配置文件也会跟随生成在安装目录下 此时你会发现,配置文 ...
- MongoDB备份(mongoexport)与恢复(mongoimport)
1.备份恢复工具介绍: mongoexport/mongoimport mongodump/mongorestore(本文未涉及) 2.备份工具区别在哪里? 2.1 mongoexport/mongo ...
- 操作系统-1w字关于内存的总结
内存的基本概念 什么是内存,有何作用 内存是用于存放数据的硬件.程序执行前需要先放入内存中才能被CPU处理 存储单元 内存中也有一个一个的小房间,每个小房间就是一个存储单元. 如果计算机按照 字节编址 ...
- 【Java集合】HashSet源码解析以及HashSet与HashMap的区别
HashSet 前言 HashSet是一个不可重复且元素无序的集合.内部使用HashMap实现. 我们可以从HashSet源码的类注释中获取到如下信息: 底层基于HashMap实现,所以迭代过程中不能 ...
- mmall商城用户模块开发总结
1.需要实现的功能介绍 注册 登录 用户名校验 忘记密码 提交问题答案 重置密码 获取用户信息 更新用户信息 退出登录 目标: 避免横向越权,纵向越权的安全漏洞 MD5明文加密级增加的salt值 Gu ...
- Linux学习笔记 | 配置ssh
目录: SSH的必要性 将默认镜像源修改为清华镜像源 Linux安装ssh软件 使用putty软件实现ssh连接 Windows下安装winscp SSH的必要性 一般服务器都位于远程而非本地,或者及 ...