博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JUC中的锁的基本概念
阅读量:758 次
发布时间:2019-03-23

本文共 5366 字,大约阅读时间需要 17 分钟。

JUC中的锁的基本概念

1.ConcurrentHashMap

在这里插入图片描述

package com.atguigu.juc;import java.util.Iterator;import java.util.concurrent.CopyOnWriteArrayList;/* * CopyOnWriteArrayList/CopyOnWriteArraySet : “写入并复制” * 注意:添加操作多时,效率低,因为每次添加时都会进行复制,开销非常的大。并发迭代操作多时可以选择。 */public class TestCopyOnWriteArrayList {
public static void main(String[] args) {
HelloThread ht = new HelloThread(); for (int i = 0; i < 10; i++) {
new Thread(ht).start(); } } }class HelloThread implements Runnable{
// private static List
list = Collections.synchronizedList(new ArrayList
()); private static CopyOnWriteArrayList
list = new CopyOnWriteArrayList<>(); static{
list.add("AA"); list.add("BB"); list.add("CC"); } @Override public void run() {
Iterator
it = list.iterator(); while(it.hasNext()){
System.out.println(it.next()); list.add("AA"); } } }

2.CountDownLatch

在这里插入图片描述

package com.atguigu.juc;import java.util.concurrent.CountDownLatch;/* * CountDownLatch :闭锁,在完成某些运算是,只有其他所有线程的运算全部完成,当前运算才继续执行 */public class TestCountDownLatch {
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(50); LatchDemo ld = new LatchDemo(latch); long start = System.currentTimeMillis(); for (int i = 0; i < 50; i++) {
new Thread(ld).start(); } try {
latch.await(); } catch (InterruptedException e) {
} long end = System.currentTimeMillis(); System.out.println("耗费时间为:" + (end - start)); }}class LatchDemo implements Runnable {
private CountDownLatch latch; public LatchDemo(CountDownLatch latch) {
this.latch = latch; } @Override public void run() {
try {
for (int i = 0; i < 50000; i++) {
if (i % 2 == 0) {
System.out.println(i); } } } finally {
latch.countDown(); } }}

3.Callable 接口

在这里插入图片描述

package com.atguigu.juc;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;/* * 一、创建执行线程的方式三:实现 Callable 接口。 相较于实现 Runnable 接口的方式,方法可以有返回值,并且可以抛出异常。 *  * 二、执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。  FutureTask 是  Future 接口的实现类 */public class TestCallable {
public static void main(String[] args) {
ThreadDemo td = new ThreadDemo(); //1.执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。 FutureTask
result = new FutureTask<>(td); new Thread(result).start(); //2.接收线程运算后的结果 try {
Integer sum = result.get(); //FutureTask 可用于 闭锁 System.out.println(sum); System.out.println("------------------------------------"); } catch (InterruptedException | ExecutionException e) {
e.printStackTrace(); } }}class ThreadDemo implements Callable
{
@Override public Integer call() throws Exception {
int sum = 0; for (int i = 0; i <= 100000; i++) {
sum += i; } return sum; } }/*class ThreadDemo implements Runnable{ @Override public void run() { } }*/

4.显示锁 Lock

在这里插入图片描述

package com.atguigu.juc;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/* * 一、用于解决多线程安全问题的方式: *  * synchronized:隐式锁 * 1. 同步代码块 *  * 2. 同步方法 *  * jdk 1.5 后: * 3. 同步锁 Lock * 注意:是一个显示锁,需要通过 lock() 方法上锁,必须通过 unlock() 方法进行释放锁 */public class TestLock {
public static void main(String[] args) {
Ticket ticket = new Ticket(); new Thread(ticket, "1号窗口").start(); new Thread(ticket, "2号窗口").start(); new Thread(ticket, "3号窗口").start(); }}class Ticket implements Runnable{
private int tick = 100; private Lock lock = new ReentrantLock(); @Override public void run() {
while(true){
lock.lock(); //上锁 try{
if(tick > 0){
try {
Thread.sleep(200); } catch (InterruptedException e) {
} System.out.println(Thread.currentThread().getName() + " 完成售票,余票为:" + --tick); } }finally{
lock.unlock(); //释放锁 } } } }

5.生产者和消费者案例

package com.atguigu.juc;/* * 生产者和消费者案例 */public class TestProductorAndConsumer {
public static void main(String[] args) {
Clerk clerk = new Clerk(); Productor pro = new Productor(clerk); Consumer cus = new Consumer(clerk); new Thread(pro, "生产者 A").start(); new Thread(cus, "消费者 B").start(); new Thread(pro, "生产者 C").start(); new Thread(cus, "消费者 D").start(); } }/*//店员class Clerk{ private int product = 0; //进货 public synchronized void get(){//循环次数:0 while(product >= 1){//为了避免虚假唤醒问题,应该总是使用在循环中 System.out.println("产品已满!"); try { this.wait(); } catch (InterruptedException e) { } } System.out.println(Thread.currentThread().getName() + " : " + ++product); this.notifyAll(); } //卖货 public synchronized void sale(){//product = 0; 循环次数:0 while(product <= 0){ System.out.println("缺货!"); try { this.wait(); } catch (InterruptedException e) { } } System.out.println(Thread.currentThread().getName() + " : " + --product); this.notifyAll(); }}//生产者class Productor implements Runnable{ private Clerk clerk; public Productor(Clerk clerk) { this.clerk = clerk; } @Override public void run() { for (int i = 0; i < 20; i++) { try { Thread.sleep(200); } catch (InterruptedException e) { } clerk.get(); } }}//消费者class Consumer implements Runnable{ private Clerk clerk; public Consumer(Clerk clerk) { this.clerk = clerk; } @Override public void run() { for (int i = 0; i < 20; i++) { clerk.sale(); } }}*/

转载地址:http://zfxzk.baihongyu.com/

你可能感兴趣的文章