技术:java8
运行环境:IDEA 15.2 + jdk8 + windows 7
demo功能:java多线程锁竞争资源demo
package com.demoworld;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by francis on 2018/4/27.
*/
public class Startup {
private static int taskCounter = 5000;
private static int threadCounter = 200;
private static int count = 0;
private static Lock lock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
reentrantLockDemo();
}
//多线程 竞争同一个资源, 锁demo, 依次输出1,2,3.。。taskCounter
private static void reentrantLockDemo() throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < taskCounter; i++) {
executorService.execute(() -> {
try {
lock.lock();
count++;
lock.unlock();
} catch (Exception ex) {
ex.printStackTrace();
}
});
}
Thread.sleep(1000L);
executorService.shutdown();
System.out.println(count);
}
private static Object object = new Object();
//多线程 计数器. 多个任务做完后, 继续做其他的事情
private static void countDownLatchDemo() throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
final CountDownLatch cdl = new CountDownLatch(taskCounter);
final Semaphore semaphore = new Semaphore(threadCounter);
for (int i = 0; i < taskCounter; i++) {
executorService.execute(() -> {
try {
semaphore.acquire();
synchronized (object) {
count++;
}
semaphore.release();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
cdl.countDown();
}
});
}
cdl.await();
executorService.shutdown();
System.out.println(count);
}
//多线程 竞争同一个资源, 同步锁demo 依次输出1,2,3.。。taskCounter
private static void lockDemo() throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < taskCounter; i++) {
executorService.execute(() -> {
try {
synchronized (object) {
add();
}
} catch (Exception ex) {
ex.printStackTrace();
}
});
}
Thread.currentThread().join();
executorService.shutdown();
}
//多线程 竞争同一个资源, 互斥 信号量 做锁 demo 依次输出1,2,3.。。taskCounter
private static void semaphoreDemo() throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(1);
for (int i = 0; i < taskCounter; i++) {
executorService.execute(() -> {
try {
semaphore.acquire();
add();
semaphore.release();
} catch (Exception ex) {
ex.printStackTrace();
}
});
}
Thread.currentThread().join();
executorService.shutdown();
}
private static void add() {
count++;
System.out.println(count);
}
}
欢迎添加微信,互相学习↑↑↑ -_-
白老虎
programming is not only to solve problems, ways to think
grafana 级连 菜单 templating (variables) 配置
rocketmq 集群搭建 (2master + 2slave + 2namesrv)
AI 机器人 抓取 微信 聊天中的 百度网盘 分享地址和密码