进程
程序的一次执行过程,是系统资源分配的单位。
线程
- 通常一个进程中可以包含多个线程,当然一个进程至少有一个线程,线程是CPU调度和执行的单位。
- 线程分为用户线程和守护线程,虚拟机必须确保用户线程执行完毕,不用等待守护线程执行完毕。
- 线程就是独立的执行路径
- 在程序运行时,即使没有自己创建线程,后台也会有多个线程,如主线程、gc线程
- main()称之为主线程,为系统的入口,用于执行整个程序
- 在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调度,调度器是与操作系统紧密相关的,先后顺序是不能人为干预的
- 对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制
- 线程会带来额外的开销,如cpu调度时间,并发控制开销
- 每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
创建线程的方式:
- 继承Thread类
- 自定义线程类继承Thread类
- 重写run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程 ,子类对象.start(),线程不一定立即执行,CPU安排调度
- 不建议使用,避免OOP单继承局限性
- 实现Runnable接口
- 定义MyRunnable类实现Runnable接口
- 实现run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程,new Thread(目标对象).start()
- 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被对个线程使用
例如:
//一份资源
StartThread4 station = new StartThread4();
//多个代理
new Thread(station,name:"小明").start();
new Thread(station,name:"老师").start();
new Thread(station,name:"小红").start();
静态代理模式
- 真实对象和代理对象都要实现同一接口
- 代理对象要代理真实角色
- 代理对象可以做很多真实对象做不了的事情
- 真实对象专注做自己的事情
- 实现Callable接口
- 实现Callable接口,需要返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象
- 创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
- 提交执行:Future result1 = ser.submit(t1);
- 获取结果: booleam r1 = result1.get()
- 关闭服务:ser.shutdownNow();
- 好处:1.可以定义返回值; 2.可以抛出异常
Lamda表达式
- 函数式接口
- 任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口。
public interface Runnable{
public abstractvoid run();
}
- 对于函数式接口,我们可以通过Lamda表达式来创建该接口的对象。
线程的状态:
- 创建状态–>就绪状态–>运行状态/阻塞状态–>死亡状态
- getState方法获取线程状态Thread.state:NEW-新生、RUNNABLE-运行、BLOCKED-阻塞、WAITING-等待,死死地等、TIMED_WAITING-超时等待、TERMINATED-终止
- 建议线程正常停止,使用flag标志位,不要使用stop或destroy等过时或者JDK不建议使用的方法
- sleep阻塞时间达到后线程进入就绪状态,可以模拟网络延时,倒计时等,区别不会释放对象锁
- yield礼让将线程由运行状态变为就绪状态,礼让不一定成功,看CPU心情
- wait/+区别
- 1.来自不同的类
wait =>Object
sleep =>Thread - 2.关于锁的释放
wait会释放锁,sleep抱着锁睡觉,不会释放 - 3.使用的范围不同
wait必须在同步代码块中
sleep可以在任何地方睡 - 4.是否需要捕获异常
wait不需要捕获异常
sleep必须要捕获异常
- 1.来自不同的类
线程同步
由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可,但存在以下问题:
- 一个线程持有锁会导致其他所有需要此锁的线程挂起
- 在多线程竞争下,加锁、释放锁会导致比较多的上下文切换和调度延时,引起性能问题
- 如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题
同步方法
- 由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种方法:synchronized方法和synchronized块
public synchronized void method(int args){}
synchronized方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才行执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行
public class Test01 {
public static void main(String[] args) {
//获取CPU的核数
//CPU密集型,IO密集型
System.out.println(Runtime.getRuntime().availableProcessors());
Ticket ticket = new Ticket();
new Thread(()->{
for (int i = 0; i < 110; i++) {
ticket.sale();
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 110; i++) {
ticket.sale();
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 110; i++) {
ticket.sale();
}
},"C").start();
}
}
class Ticket{
private int number = 100;
public synchronized void sale() {
if(number > 0){
System.out.println(Thread.currentThread().getName()+"卖出了"+(number--)+"票,剩余:"+number);
}
}
}
同步块
- synchronized (obj){}
- obj称之为同步监视器
- obj可以是任何对象,但是推荐使用共享资源作为同步监视器
- 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class
- 同步监视器的执行过程
- 第一个线程访问,锁定同步监视器,执行其中代码
- 第二个线程访问,发现同步监视器被锁定,无法访问
- 第一个线程访问完毕,解锁同步监视器
- 第二个线程访问,发现同步监视器没有锁,然后锁定并访问
Lock锁
实现类:
可重入锁(常用)、读锁、写锁
ReentrantLock , ReentrantReadWriteLock.ReadLock , ReentrantReadWriteLock.WriteLock
Lock l = ...; l.lock(); try { // access the resource protected by this lock } finally { l.unlock(); }
公平锁FairSync() :十分公平,先来后到
公平锁NonfairSync():十分不公平,可以插队(默认)
public class Test01 {
public static void main(String[] args) {
//获取CPU的核数
//CPU密集型,IO密集型
System.out.println(Runtime.getRuntime().availableProcessors());
Ticket ticket = new Ticket();
new Thread(()->{for (int i = 0; i < 110; i++) ticket.sale();},"A").start();
new Thread(()->{for (int i = 0; i < 110; i++) ticket.sale();},"B").start();
new Thread(()->{for (int i = 0; i < 110; i++) ticket.sale();},"C").start();
}
}
class Ticket{
private int number = 100;
Lock lock = new ReentrantLock();
public void sale() {
lock.lock();
try {
if(number > 0){
System.out.println(Thread.currentThread().getName()+"卖出了"+(number--)+"票,剩余:"+number);
}
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
Synchronized和Lock区别:
- Synchronized是内置的java关键字;Lock是一个java类
- Synchronized无法判断获取锁的状态;Lock可以判断是否获取到了锁
- Synchronized会自动释放;Lock必须要手动释放锁!如果不释放,可能出现死锁
- Synchronized线程1(获得锁,阻塞),线程2(等待,傻傻地等);Lock锁就不一定会等待下去
- Synchronized可重入锁,不可中断的,非公平;Lock可重入锁,可以判断,非公平(可以自己设置)
- Synchronized适合锁少量的代码同步问题;Lock适合锁大量的同步代码
死锁
产生死锁的四个必要条件:
- 互斥条件:一个资源每次只能被一个进程使用
- 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
- 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺
- 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
生产者和消费者问题
使用Synchronized版
public class A {
public static void main(String[] args) {
Data data = new Data();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B").start();
}
}
//判断等待,业务,通知
class Data{
private int num = 0;
public synchronized void increment() throws InterruptedException {
if(num!=0){
this.wait();
}
num++;
System.out.println(Thread.currentThread().getName()+"=>"+num);
this.notifyAll();
}
public synchronized void decrement() throws InterruptedException {
if(num==0){
this.wait();
}
num--;
System.out.println(Thread.currentThread().getName()+"=>"+num);
this.notifyAll();
}
}
问题存在,A,B,C,D 4个线程
线程也可以唤醒,而不会被通知,中断或超时,即所谓的虚假唤醒 。 虽然这在实践中很少会发生,但应用程序必须通过测试应该使线程被唤醒的条件来防范,并且如果条件不满足则继续等待。 换句话说,等待应该总是出现在循环中,就像这样:
synchronized (obj) {
while ()
obj.wait(timeout);
… // Perform action appropriate to condition
}
if改成while判断
public class A {
public static void main(String[] args) {
Data data = new Data();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"C").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"D").start();
}
}
//判断等待,业务,通知
class Data{
private int num = 0;
public synchronized void increment() throws InterruptedException {
while(num!=0){
this.wait();
}
num++;
System.out.println(Thread.currentThread().getName()+"=>"+num);
this.notifyAll();
}
public synchronized void decrement() throws InterruptedException {
while(num==0){
this.wait();
}
num--;
System.out.println(Thread.currentThread().getName()+"=>"+num);
this.notifyAll();
}
}
使用Lock版
public class B {
public static void main(String[] args) {
Data2 data2 = new Data2();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data2.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data2.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data2.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"C").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data2.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"D").start();
}
}
//判断等待,业务,通知
class Data2{
private int num = 0;
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
//condition.await();
//condition.signalAll();
public void increment() throws InterruptedException {
lock.lock();
try{
while(num!=0){
condition.await();
}
num++;
System.out.println(Thread.currentThread().getName()+"=>"+num);
condition.signalAll();
}catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public synchronized void decrement() throws InterruptedException {
lock.lock();
try{
while(num==0){
condition.await();
}
num--;
System.out.println(Thread.currentThread().getName()+"=>"+num);
condition.signalAll();
}catch(Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
问题:执行顺序随机性,不确定
使用Condition优化,实现精准通知唤醒
public class C {
public static void main(String[] args) {
Data3 data3 = new Data3();
new Thread(()->{for (int i = 0; i < 10; i++) data3.printA();},"A").start();
new Thread(()->{for (int i = 0; i < 10; i++) data3.printB();},"B").start();
new Thread(()->{for (int i = 0; i < 10; i++) data3.printC();},"C").start();
}
}
class Data3{
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
private int number = 1;
public void printA(){
lock.lock();
try {
while(number!=1){
condition1.await();
}
System.out.println(Thread.currentThread().getName()+"=>"+number);
number++;
condition2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printB(){
lock.lock();
try {
while(number!=2){
condition2.await();
}
System.out.println(Thread.currentThread().getName()+"=>"+number);
number++;
condition3.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printC(){
lock.lock();
try {
while(number!=3){
condition3.await();
}
System.out.println(Thread.currentThread().getName()+"=>"+number);
number=number-2;
condition1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
八锁现象
深刻理解锁
import java.util.concurrent.TimeUnit;
/**
* 8锁,就是关于锁的8个问题
* 1.标准情况下,两个线程先打印发短信还是打电话? 发短信
* 2.sendMsg延迟4秒,两个线程先打印发短信还是打电话? 发短信
*/
public class Test1 {
public static void main(String[] args) {
Phone phone = new Phone();
new Thread(()->{
phone.sendMsg();
},"A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone.call();
},"B").start();
}
}
class Phone{
// synchronized 锁的对象是方法的调用者
// 两个方法用的同一把锁,谁先拿到谁执行
public synchronized void sendMsg(){
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
public synchronized void call(){
System.out.println("打电话");
}
}
import java.util.concurrent.TimeUnit;
/**
* 3. 增加了一个普通方法后,先执行发短信还是hello? hello
* 4. 两个对象,两个同步方法,先执行发短信还是打电话? 打电话
*/
public class Test2 {
public static void main(String[] args) {
Phone2 phone1 = new Phone2();
Phone2 phone2 = new Phone2();
new Thread(()->{
phone1.sendMsg();
},"A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone2.call();
},"B").start();
}
}
class Phone2{
// synchronized 锁的对象是方法的调用者
public synchronized void sendMsg(){
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
public synchronized void call(){
System.out.println("打电话");
}
public void hello(){
System.out.println("hello");
}
}
import java.util.concurrent.TimeUnit;
/**
* 5.增加两个静态的同步方法,只有一个对象,先打印发短信还是打电话? 发短信
* 6.两个对象,增加两个静态的同步方法,只有一个对象,先打印发短信还是打电话? 发短信
*/
public class Test3 {
public static void main(String[] args) {
//两个对象的Class模板只有一个,static,锁的是Class
Phone3 phone1 = new Phone3();
Phone3 phone2 = new Phone3();
new Thread(()->{
phone1.sendMsg();
},"A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone2.call();
},"B").start();
}
}
class Phone3{
// synchronized 锁的对象是方法的调用者
// static 静态方法
// 类一加载就有了,锁的是Class
public static synchronized void sendMsg(){
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
public static synchronized void call(){
System.out.println("打电话");
}
}
import java.util.concurrent.TimeUnit;
/**
* 7.一个静态同步方法,一个普通同步方法,一个对象,先打印发短信还是打电话? 打电话
* 8.一个静态同步方法,一个普通同步方法,两个个对象,先打印发短信还是打电话? 打电话
*/
public class Test4 {
public static void main(String[] args) {
//两个对象的Class模板只有一个,static,锁的是Class
Phone4 phone1 = new Phone4();
Phone4 phone2 = new Phone4();
new Thread(()->{
phone1.sendMsg();
},"A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone2.call();
},"B").start();
}
}
class Phone4{
//静态同步方法,锁的是Class类模板
public static synchronized void sendMsg(){
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
//普通同步方法,锁的是使用者
public synchronized void call(){
System.out.println("打电话");
}
}
小结
new this 具体的一个对象
static CLass唯一的一个模板
集合类不安全
List不安全
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
//java.util.ConcurrentModificationException 并发修改异常
public class ListTest {
public static void main(String[] args) {
//并发下ArrayList不安全的
/**
* 解决方案
* 1.List<String> list = new Vector<>();
* 2.List<String> list = Collections.synchronizedList(new ArrayList<>());
* 3.List<String> list = new CopyOnWriteArrayList<>();
*/
// CopyOnWrite 写入时复制 COW 计算机程序设计领域的一种优化策略;
// 多个线程调用的时候,list,读取的时候,固定的,写入(覆盖)
// 在写入的时候避免覆盖,造成数据问题
// CopyOnWriteArrayList 比 Vector 优势在哪里? CopyOnWriteArrayList add方法使用的Lock锁, Vector add方法使用的 synchronized
List<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 10; i++) {
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(list);
},String.valueOf(i)).start();
}
}
}
Set不安全
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* Set多线程同样出现 java.util.ConcurrentModificationException
* 解决方案:
* 1.Set<String> set = Collections.synchronizedSet(new HashSet<>())
* 2.Set<String> set = new CopyOnWriteArraySet<>();
*/
public class SetTest {
public static void main(String[] args) {
//Set<String> set = new HashSet<>();
//Set<String> set = Collections.synchronizedSet(new HashSet<>());
Set<String> set = new CopyOnWriteArraySet<>();
for (int i = 0; i < 30; i++) {
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(set);
},String.valueOf(i)).start();
}
}
}
Map不安全
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Map多线程同样出现 java.util.ConcurrentModificationException
* 解决方案:
* 1.Map<String, String> map = Collections.synchronizedMap(new HashMap<>())
* 2.Map<String, String> map = new ConcurrentHashMap<>()
*/
public class MapTest {
public static void main(String[] args) {
//Map<String, String> map = new HashMap<>();
//Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
Map<String, String> map = new ConcurrentHashMap<>();
for (int i = 0; i < 30; i++) {
new Thread(()->{
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
System.out.println(map);
},String.valueOf(i)).start();
}
}
}
Callable
与 Runnable差别
- 有返回值
- 可以抛出异常
- 方法不同,run()/ call()
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//new Thread(new Runnable()).start();
//new Thread(new FutureTask<V>()).start();
//new Thread(new FutureTask<V>(Callable)).start();
MyThread thread = new MyThread();
FutureTask futureTask = new FutureTask(thread); //适配类
new Thread(futureTask,"A").start();
new Thread(futureTask,"B").start(); //结果会被缓存,效率高
Integer i = (Integer) futureTask.get(); //获取Callable的返回结果,可能导致阻塞
System.out.println(i);
}
}
class MyThread implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("call()");
return 12345;
}
}
常用的辅助类
- CountDownLatch
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i < 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"Go out");
countDownLatch.countDown(); //数量-1
},String.valueOf(i)).start();
}
countDownLatch.await(); //等待计数器归零,然后再向下执行
System.out.println("Close Door");
}
}
- CyclicBarrier
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println("召唤神龙");
});
for (int i = 1; i <= 7; i++) {
final int temp = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"收集"+temp+"龙珠");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}
- Semaphore
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);
for (int i = 1; i <= 6; i++) {
new Thread(()->{
//acquire() 得到
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"抢到车位");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+"离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//release() 释放
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}
semaphore.acquire() 获得,假设已经满了,等待,等到被释放为止
semaphore.release() 释放,会将当前的信号量释放+1,然后唤醒等待的线程
作用:多个共享资源互斥时使用,控制最大的线程数
读写锁
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockDemo {
public static void main(String[] args) {
MyCacheLock myCacheLock = new MyCacheLock();
for (int i = 1; i <= 5; i++) {
final int temp = i;
new Thread(()->{
myCacheLock.put(temp+"",temp+"");
},String.valueOf(i)).start();
}
for (int i = 1; i <= 5; i++) {
final int temp = i;
new Thread(()->{
myCacheLock.get(temp+"");
},String.valueOf(i)).start();
}
}
}
class MyCache{
private volatile Map<String,Object> map = new HashMap<>();
public void put(String key,Object value){
System.out.println(Thread.currentThread().getName()+"写入"+key);
map.put(key,value);
System.out.println(Thread.currentThread().getName()+"写入ok");
}
public void get(String key){
System.out.println(Thread.currentThread().getName()+"读取"+key);
map.get(key);
System.out.println(Thread.currentThread().getName()+"读取ok");
}
}
class MyCacheLock{
private volatile Map<String,Object> map = new HashMap<>();
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public void put(String key,Object value){
readWriteLock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName()+"写入"+key);
map.put(key,value);
System.out.println(Thread.currentThread().getName()+"写入ok");
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.writeLock().unlock();
}
}
public void get(String key){
readWriteLock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName()+"读取"+key);
map.get(key);
System.out.println(Thread.currentThread().getName()+"读取ok");
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.readLock().unlock();
}
}
}
阻塞队列BlockingQueue
方式 | 抛出异常 | 有返回值 | 阻塞等待 | 超时等待 |
---|---|---|---|---|
添加 | add() | offer() | put() | offer(timeout) |
删除 | remove() | poll() | take() | poll(timeout) |
检测队首元素 | element() | peek() | - | - |
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
public class BlockingQueueTest {
public static void main(String[] args) throws InterruptedException {
test1();
test2();
test3();
test4();
}
/**
* 抛出异常
*/
public static void test1(){
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
//IllegalStateException:Queue full
//System.out.println(blockingQueue.add("d"));
//查看队首元素
System.out.println(blockingQueue.element());
System.out.println("============================");
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
//java.util.NoSuchElementException
//System.out.println(blockingQueue.remove());
}
/**
* 不抛出异常,会有返回值
*/
public static void test2(){
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
//返回false 不抛出异常
//System.out.println(blockingQueue.offer("d"));
//查看队首元素
System.out.println(blockingQueue.peek());
System.out.println("==============================");
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
//返回null 不抛出异常
//System.out.println(blockingQueue.poll());
}
/**
* 等待,阻塞(一直阻塞)
*/
public static void test3() throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
blockingQueue.put("a");
blockingQueue.put("b");
blockingQueue.put("c");
//队列没有位置,一直等待
//blockingQueue.put("d");
System.out.println("==============================");
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
//没有队列元素,一直等待
//System.out.println(blockingQueue.take());
}
/**
* 等待,阻塞(等待超时)
*/
public static void test4() throws InterruptedException{
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
//等待超过2秒就退出
//System.out.println(blockingQueue.offer("d",2, TimeUnit.SECONDS));
System.out.println("==============================");
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
//等待超过2秒就退出
//System.out.println(blockingQueue.poll(2,TimeUnit.SECONDS));
}
}
同步队列 SynchronousQueue
进去一个元素,必须等待取出来之后,才能再往里面放一个元素
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
public class SynchronousQueueTest {
public static void main(String[] args) throws InterruptedException {
test();
}
public static void test(){
BlockingQueue<String> queue = new SynchronousQueue<String>();
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName()+" put 1");
queue.put("1");
System.out.println(Thread.currentThread().getName()+" put 2");
queue.put("2");
System.out.println(Thread.currentThread().getName()+" put 3");
queue.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
}
},"T1").start();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+" take "+queue.take());
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+" take "+queue.take());
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+" take "+queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
},"T2").start();
}
}
线程池
池化技术:为充分利用CPU,事先准备好一些资源,有人要用就来我这拿,用完之后还给我
线程池的好处:
- 降低资源的消耗
- 提高响应的速度
- 方便管理
线程复用、可以控制最大并发数、管理线程
- 程池三大方法:
newSingleThreadExecutor() 单个线程
newFixedThreadPool(5) 固定大小的线程池
newCachedThreadPool() 可变大小的线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Demo01 {
public static void main(String[] args) {
ExecutorService threadpool = Executors.newSingleThreadExecutor();//单个线程
//ExecutorService threadpool = Executors.newFixedThreadPool(5);//创建一个固定大小的线程池
//ExecutorService threadpool = Executors.newCachedThreadPool();//创建一个可变大小的线程池
try {
for (int i = 0; i < 100; i++) {
//使用线程池创建线程
threadpool.execute(()->{
System.out.println(Thread.currentThread().getName()+"ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadpool.shutdownNow();
}
}
}
- 线程池七大参数:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
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;
}
自定义线程池
import java.util.concurrent.*;
public class Demo2 {
public static void main(String[] args) {
ExecutorService threadpool = new ThreadPoolExecutor(2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
try {
//最大承载 = 队列长度 +
for (int i = 0; i < 8; i++) {
threadpool.execute(()->{
System.out.println(Thread.currentThread().getName()+"ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadpool.shutdown();
}
}
}
- 线程池四种拒绝策略:
- AbortPolicy() 队列满了,抛出异常java.util.concurrent.RejectedExecutionException
- CallerRunsPolicy() 哪来的去哪里
- DiscardPolicy() 队列满了,丢掉任务,不会抛出异常
- DiscardOldestPolicy() 队列满了,尝试去和最早的竞争,也不会抛出异常
线程池的最大线程数到底如何定义?
- CPU密集型,几核CPU就定义为几,可以保持CPU的效率最高Runtime.getRuntime().availableProcessors()
- IO密集型,判断程序中十分耗IO的线程
四大函数式接口
函数式接口:只有一个方法的接口
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
四大原生函数式接口:Consumer、Function、Predicate、Supplier
import java.util.function.Function;
/**
* Function 函数型接口,有一个输入参数,一个输出参数
* 只要是函数式接口,可以用lambda表达式简化
*/
public class Demo01 {
public static void main(String[] args) {
/*Function<String,String> function = new Function<String,String>(){
@Override
public String apply(String str) {
return str;
}
};*/
Function function = (str)->{return str;};
System.out.println(function.apply("abc"));
}
}
import java.util.function.Predicate;
/**
* Predicate判断型接口,有一个输入参数,返回值只能是布尔值
*/
public class Demo02 {
public static void main(String[] args) {
/*Predicate<String> predicate = new Predicate<String>(){
@Override
public boolean test(String str){
return str.isEmpty();
}
};*/
Predicate<String> predicate = (str)->{return str.isEmpty();};
System.out.println(predicate.test(""));
}
}
import java.util.function.Consumer;
/**
* Consumer 消费型接口,只有输入,没有返回值
*/
public class Demo03 {
public static void main(String[] args) {
/*Consumer<String> consumer = new Consumer<String>() {
@Override
public void accept(String str) {
System.out.println(str);
}
};*/
Consumer<String> consumer = (str)->{System.out.println(str);};
consumer.accept("abc");
}
}
import java.util.function.Supplier;
/**
* Supplier 供给型接口,没有参数,有返回值
*/
public class Demo04 {
public static void main(String[] args) {
/*Supplier<Integer> supplier = new Supplier<Integer>() {
@Override
public Integer get() {
System.out.println("get()");
return 1024;
}
};*/
Supplier<Integer> supplier = ()->{return 1024;};
System.out.println(supplier.get());
}
}
Stream流式计算
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
/**从5个用户筛选:
* 1.ID必须是偶数
* 2.年龄必须大于23岁
* 3.用户名转为大写字母
* 4.用户名字母倒着排序
* 5.只输出一个用户
*/
public class Test {
public static void main(String[] args) {
User u1 = new User(1,"a",21);
User u2 = new User(2,"b",22);
User u3 = new User(3,"c",23);
User u4 = new User(4,"d",24);
User u5 = new User(6,"e",25);
List<User> list = Arrays.asList(u1, u2, u3, u4, u5);
list.stream()
.filter((u)->{return u.getId()%2==0;})
.filter((u)->{return u.getAge()>23;})
.map((u)->{return u.getName().toUpperCase();})
.sorted((uu1,uu2)->{return uu2.compareTo(uu1);})
.limit(1)
.forEach(System.out::println);
}
}
ForkJoin
ForkJoin并行执行任务,提高效率,大数据量
大数据:Map Reduce (把大任务拆分为)
特点:双端队列,工作窃取
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;
public class test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
test1();
test2();
test3();
}
public static void test1(){
Long sum = 0L;
long start = System.currentTimeMillis();
for (Long i = 1L; i <= 10_000_000; i++) {
sum += i;
}
long end = System.currentTimeMillis();
System.out.println("sum="+sum+"时间:"+(end-start));
}
public static void test2() throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTask<Long> task = new Demo01(0L,10_000_000L);
ForkJoinTask<Long> submit = forkJoinPool.submit(task);
Long sum = submit.get();
long end = System.currentTimeMillis();
System.out.println("sum="+sum+"时间:"+(end-start));
}
public static void test3(){
long start = System.currentTimeMillis();
Long sum = LongStream.rangeClosed(0L,10_000_000L).parallel().reduce(0,Long::sum);
long end = System.currentTimeMillis();
System.out.println("sum="+sum+"时间:"+(end-start));
}
}
异步回调
Future设计的初衷:对将来的某个事件的结果进行建模
import com.sun.corba.se.impl.orbutil.closure.Future;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* 异步调用:Ajax
* 异步执行
* 成功回调
* 失败回调
*/
public class Demo01 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//没有返回值的 runAsync 异步回调
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"runAsync=>Void");
});
System.out.println("1111");
completableFuture.get();
//有返回值的 supplyAsync 异步回调
CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(()->{
System.out.println(Thread.currentThread().getName()+"supplyAsync=>Integer");
int i = 10/0;
return 1024;
});
completableFuture1.whenComplete((t,u)->{
System.out.println("t=>"+t); //正常的返回值
System.out.println("u=>"+u); //错误信息,java.util.concurrent.CompletionException
}).exceptionally((e)->{
System.out.println(e.getMessage());
return 233;
}).get();
}
}
理解 JMM
Volatile是java虚拟机提供轻量级的同步机制
- 保证可见性
import java.util.concurrent.TimeUnit;
public class JMMDemo {
//不加volatile,程序就会死循环
//加 volatile 可以保证可见性
private volatile static int num = 0;
public static void main(String[] args) {
new Thread(()->{
while(num==0){
}
}).start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
num = 1;
System.out.println(num);
}
}
- 不保证原子性
public class VDemo02 {
//volatile不保证原子性
private volatile static int num = 0;
public static void add(){
num++; //不是一个原子性操作:1.获取这个值;2.+1;3.写入这个值
}
public static void main(String[] args) {
//理论上num结果应该是500000
for (int i = 1; i <= 500; i++) {
new Thread(()->{
for (int i1 = 0; i1 < 1000; i1++) {
add();
}
}).start();
}
while(Thread.activeCount()>2){
Thread.yield();
}
System.out.println(Thread.currentThread().getName()+" "+num);
}
}
如果不加lock和synchronized,怎么保证原子性?
使用原子类,解决原子性问题
import java.util.concurrent.atomic.AtomicInteger;
public class VDemo02 {
//volatile不保证原子性
private volatile static AtomicInteger num = new AtomicInteger();
public static void add(){
//num++;
num.getAndIncrement(); //AtomicInteger+1
}
public static void main(String[] args) {
//理论上num结果应该是500000
for (int i = 1; i <= 500; i++) {
new Thread(()->{
for (int i1 = 0; i1 < 1000; i1++) {
add();
}
}).start();
}
while(Thread.activeCount()>2){
Thread.yield();
}
System.out.println(Thread.currentThread().getName()+" "+num);
}
}
这些类的底层都直接和操作系统挂钩,在内存中修改值!Unsafe类是一个很特殊的存在
3. 禁止指令重排
什么是指令重排?你写的程序,计算机并不是按照你写的那样去执行的。
源代码–>编译器优化的重排–>指令并行也可能会重排–>内存系统也会重排–>执行
处理器在进行指令重排的时候,考虑:数据之间的依赖性
volatile可以避免指令重排:
内存屏障,CPU指令,作用:
- 保证特定的操作执行顺序
- 可以保证某些变量的内存可见性
JMM:java内存模型,是一个约定、概念
线程 工作内存、主内存
关于JMM的一些同步约定: - 线程解锁前,必须把共享变量立刻刷回主存
- 线程加锁前,必须读取主存中的最新值到工作内存中
- 加锁和解锁是同一把锁
内存交互的八种操作
lock (锁定):作用于主内存的变量,把一个变量标识为线程独占状态
unlock (解锁):作用于主内存的变量,它把一个处于锁定状态的变量释放出来,释放后的变量才可以被其他线程锁定
read (读取):作用于主内存变量,它把一个变量的值从主内存传输到线程的工作内存中,以便随后的load动作使用
load (载入):作用于工作内存的变量,它把read操作从主存中变量放入工作内存中
use (使用):作用于工作内存中的变量,它把工作内存中的变量传输给执行引擎,每当虚拟机遇到一个需要使用到变量的值,就会使用到这个指令
assign (赋值):作用于工作内存中的变量,它把一个从执行引擎中接受到的值放入工作内存的变量副本中
store (存储):作用于主内存中的变量,它把一个从工作内存中一个变量的值传送到主内存中,以便后续的write使用
write (写入):作用于主内存中的变量,它把store操作从工作内存中得到的变量的值放入主内存的变量中
对这八种指令的使用,制定了如下规则:
- 不允许read和load、store和write操作之间单独出现。即使用了read必须load,使用了store必须write
- 不允许线程丢弃他最近的assign操作,即工作变量的数据改变了之后,必须告知主存
- 不允许一个线程将没有assign的数据从工作内存同步回主内存
- 一个新的变量必须在主内存中诞生,不允许工作内存直接使用一个未被初始化的变量。就是对变量实施use、store操作之前,必须经过assign和load操作
- 一个变量同一时间只有一个线程能对其进行lock。多次lock后,必须执行相同次数的unlock才能解锁
- 如果对一个变量进行lock操作,会清空所有工作内存中此变量的值,在执行引擎使用这个变量前,必须重新load或assign操作始化变量的值
- 如果一个变量没有被lock,就不能对其进行unlock操作。也不能unlock一个被其他线程锁住的变量
- 对一个变量进行unlock操作之前,必须把此变量同步回主内存
单例模式
饿汉式
//饿汉式单例
public class Hungry {
private Hungry(){
}
private final static Hungry HUNGRY = new Hungry();
public static Hungry getInstance(){
return HUNGRY;
}
}
懒汉式
//懒汉式单例
public class LazyMan {
private LazyMan(){
System.out.println(Thread.currentThread().getName()+"ok");
}
private volatile static LazyMan lazyMan;
//双重检测锁模式的懒汉式单例,DCL懒汉式
public static LazyMan getInstance() {
if(lazyMan==null){
synchronized (LazyMan.class){
if(lazyMan==null){
lazyMan = new LazyMan();
}
}
}
return lazyMan;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(()->{
LazyMan.getInstance();
}).start();
}
}
}
静态内部类
//静态内部类
public class Holder {
private Holder(){
}
public static Holder getInstance(){
return InnerClass.HOLDER;
}
public static class InnerClass{
private static final Holder HOLDER = new Holder();
}
}
import java.lang.reflect.Constructor;
//enum是一个什么?本身也是一个class类
public enum EnumSingle {
INSTANCE;
public EnumSingle getInstance(){
return INSTANCE;
}
}
class test{
public static void main(String[] args) throws Exception {
EnumSingle instance1 = EnumSingle.INSTANCE;
Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(String.class,int.class);
declaredConstructor.setAccessible(true);
EnumSingle instance2 = declaredConstructor.newInstance();
System.out.println(instance1);
System.out.println(instance2);
}
}
CAS
import java.util.concurrent.atomic.AtomicInteger;
public class CASDemo {
//CAS compareAndSet :比较并交换
public static void main(String[] args) {
AtomicInteger atomicInteger = new AtomicInteger(2020);
//public final boolean compareAndSet(int expect, int update)
//如果期望的值达到了,那么就更新,否则,就不更新,CAS是CPU的并发原语
System.out.println(atomicInteger.compareAndSet(2020, 2021));
System.out.println(atomicInteger.get());
atomicInteger.getAndIncrement();
System.out.println(atomicInteger.compareAndSet(2020, 2021));
System.out.println(atomicInteger.get());
}
}
CAS:比较当前工作内存中的值和主内存中的值,如果这个值是期望的,那么则执行操作!如果不是就一直循环!
缺点:
- 底层是一个自旋锁,循环会耗时
- 一次性只能保证一个共享变量的原子性
- 存在ABA问题(原子引用解决)
原子引用
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;
public class CASDemo {
static AtomicStampedReference<Integer> atomicStampedReference= new AtomicStampedReference<>(1,1);
//CAS compareAndSet :比较并交换
public static void main(String[] args) {
//AtomicInteger atomicInteger = new AtomicInteger(2020);
//public final boolean compareAndSet(int expect, int update)
//如果期望的值达到了,那么就更新,否则,就不更新,CAS是CPU的并发原语
new Thread(()->{
int stamp = atomicStampedReference.getStamp(); //获得版本号
System.out.println("a1=>"+stamp);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
atomicStampedReference.compareAndSet(1,2,atomicStampedReference.getStamp(),atomicStampedReference.getStamp()+1);
System.out.println("a2=>"+atomicStampedReference.getStamp());
System.out.println(atomicStampedReference.compareAndSet(2, 1, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));
System.out.println("a3=>"+atomicStampedReference.getStamp());
},"a").start();
new Thread(()->{
int stamp = atomicStampedReference.getStamp(); //获得版本号
System.out.println("b1=>"+stamp);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(atomicStampedReference.compareAndSet(1, 6, stamp, stamp + 1));
System.out.println("b2=>"+atomicStampedReference.getStamp());
},"b").start();
}
}
锁的分类
- 公平锁、非公平锁
公平锁:不能够插队,必须先来后到
非公平锁:可以插队(默认都是非公平锁)
public ReentrantLock() {
sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
- 可重入锁
可重入锁(递归锁):拿到了外面的锁之后,就可以拿到里面的锁,自动获得
//synchronized
public class Demo01 {
public static void main(String[] args) {
Phone phone = new Phone();
new Thread(()->{
phone.sms();
},"A").start();
new Thread(()->{
phone.sms();
},"B").start();
}
}
class Phone{
public synchronized void sms(){
System.out.println(Thread.currentThread().getName()+"sms");
call();
}
public synchronized void call(){
System.out.println(Thread.currentThread().getName()+"call");
}
}
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Demo02 {
public static void main(String[] args) {
Phone2 phone2 = new Phone2();
new Thread(()->{
phone2.sms();
},"A").start();
new Thread(()->{
phone2.sms();
},"B").start();
}
}
class Phone2{
Lock lock = new ReentrantLock();
public void sms(){
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+"sms");
call();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void call(){
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+"call");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
- 自旋锁
public final int getAndAddInt(Object var1, long var2, int var4) {
int var5;
do {
var5 = this.getIntVolatile(var1, var2);
} while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
return var5;
}
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* 自旋锁
*/
public class SpinLock {
AtomicReference<Thread> atomicReference = new AtomicReference<>();
//加锁
public void myLock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName()+"==> myLock");
//自旋锁
while(!atomicReference.compareAndSet(null,thread)){
}
}
//解锁
public void myUnLock(){
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName()+"==> myUnLock");
//自旋锁
atomicReference.compareAndSet(thread,null);
}
public static void main(String[] args) {
SpinLock lock = new SpinLock();
new Thread(()->{
lock.myLock();
try {
TimeUnit.SECONDS.sleep(5);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.myUnLock();
}
},"T1").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
lock.myLock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.myUnLock();
}
},"T2").start();
}
}
- 死锁
死锁测试,怎么排查?
import java.util.concurrent.TimeUnit;
public class DeadLock {
public static void main(String[] args) {
String lockA = "lockA";
String lockB = "lockB";
new Thread(new MyThread(lockA,lockB),"T1").start();
new Thread(new MyThread(lockB,lockA),"T2").start();
}
}
class MyThread implements Runnable{
private String lockA;
private String lockB;
public MyThread(String lockA, String lockB) {
this.lockA = lockA;
this.lockB = lockB;
}
@Override
public void run() {
synchronized (lockA){
System.out.println(Thread.currentThread().getName()+"lock"+lockA+"=>get"+lockB);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockB){
System.out.println(Thread.currentThread().getName()+"lock"+lockB+"=>get"+lockA);
}
}
}
}
解决问题
- 使用 ‘jps -l’ 定位进程号
- 使用 'jstack 进程号’查看进程信息