多线程详解
进程 一个进程可以有多个线程,如视频中同时听声音,看图像,看弹幕,等等
程序是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念。
进程是执行程序的一次执行过程,它是动态的概念。是系统资源分配的单位
通常在一个进程中可以包含若干个线程,当然一个进程至少有一个线程,不然没有存在的意义。线程是CPU调度和执行的单位。
注意:不少多线程都是模拟出来的,真正的多线程是指有多个CPU,即多核,如服务器。如果是模拟出来的多线程,即在一个CPU的情况下,在同一时间点,cpu只能执行一个代码,因为切换的很快,所以有同时执行的错觉。
总结:
线程就是独立的执行路径;
在程序运行时,即使没有自己创建线程,后台也会有多个线程,如主线程,gc线程;
main()称之为主线程,为系统的入口,用于执行整个程序;
在一个进程中,如果开辟了多个线程,线程的运行由调度器(CPU)安排调度,调度器是与操作系统紧密相关的,先后顺序是不能人为的干预的。
对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制。
线程会带来额外的开销,如cpu调度时间,并发控制开销。
每个线程在自己的工作内存交互,内存控制不当会造成数据不一致;
多线程 原来的方法调用 vs 多线程下的方法调用
线程实现 继承Thread类 继承Thread类实现多线程步骤如下:
自定义线程类继承Thread类
重写run() 方法,编写线程执行体
创建线程对象,调用start() 方法启动线程
通过查看源码发现Thread 是实现Runnable接口的。 注意:线程开启不一定立即执行,由CPU调度安排。
1 2 3 4 5 6 7 8 9 10 11 12 13 public class TestThread1 extends Thread { @Override public void run () { for (int i = 0 ; i < 5 ; i++) { System.out.println("我在撸代码--" +i); } } public static void main (String[] args) { TestThread1 testThread1 = new TestThread1(); testThread1.start(); for (int i = 0 ; i < 5 ; i++) { System.out.println("我在学习--" +i); } } }
1 2 3 4 5 6 7 8 9 10 我在学习--0 我在学习--1 我在撸代码--0 我在学习--2 我在学习--3 我在撸代码--1 我在撸代码--2 我在撸代码--3 我在学习--4 我在撸代码--4
网图下载 下载jar
http://commons.apache.org/ -左Release-右IO-Binaries
commons-io-2.11.0-bin.zip(Win)
commons-io-2.11.0-bin.tar.gz(Linux)
添加库(jar)
右键com-New-Package-lib-[ctrl+v]
右键lib-AddasLibrary
name:lib,level和Addtomodule默认
ProjectStruct-ProjectSettings-Libraries-可以看到库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 package com.humble.thread;import org.apache.commons.io.FileUtils;import java.io.File;import java.io.IOException;import java.net.URL;public class TestThread2 extends Thread { private String url; private String name; public TestThread2 (String url,String name) { this .name = name; this .url = url; } @Override public void run () { WebDownloader webDownloader = new WebDownloader(); webDownloader.downLoader(url,name); System.out.println("下载了文件名为:" +name); } public static void main (String[] args) { TestThread2 thread1 = new TestThread2("http://192.168.1.1/tmp/a.jpg" , "1.jpg" ); TestThread2 thread2 = new TestThread2("http://192.168.1.1/tmp/b.jpg" , "2.jpg" ); TestThread2 thread3 = new TestThread2("http://192.168.1.1/tmp/c.jpg" , "3.jpg" ); thread1.start(); thread2.start(); thread3.start(); } } class WebDownloader { public void downLoader (String url,String name) { try { FileUtils.copyURLToFile(new URL(url),new File(name)); } catch (IOException e) { e.printStackTrace(); System.out.println("IO 异常,Downloader方法出现问题" ); } } }
1 2 3 下载了文件名为:2.jpg 下载了文件名为:1.jpg 下载了文件名为:3.jpg
实现Runnable 接口 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package com.humble.thread;public class TestThread3 implements Runnable { @Override public void run () { for (int i = 0 ; i < 5 ; i++) { System.out.println("我在撸代码--" +i); } } public static void main (String[] args) { TestThread3 testThread3 = new TestThread3(); Thread thread = new Thread(testThread3); thread.start(); for (int i = 0 ; i < 5 ; i++) { System.out.println("我在学习--" +i); } } }
1 2 3 4 5 6 7 8 9 10 我在学习--0 我在学习--1 我在撸代码--0 我在学习--2 我在学习--3 我在撸代码--1 我在撸代码--2 我在撸代码--3 我在学习--4 我在撸代码--4
Thread 和Runnable小结 继承Thread类
子类继承Thread 类具有多线程能力
启动线程:子类对象.start()
不建议使用:避免OOP单继承局限性
实现Runnable 接口
实现接口Runnable 具有多线程能力
启动线程:传入目标对象+Thread对象.start()
推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
案例:龟兔赛跑
首先来个赛道距离,然后要离终点越来越近
判断比赛是否结束
打印出胜利者
龟兔赛跑开始
故事中是乌龟赢了,兔子需要睡觉,所以我们模拟兔子睡觉
终于,乌龟赢了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 package com.humble.thread;public class Race implements Runnable { private static String winner; @Override public void run () { for (int i = 1 ; i <= 100 ; i++) { if (Thread.currentThread().getName().equals("兔子" ) && i % 10 == 0 ) { try { Thread.sleep(10 ); } catch (InterruptedException e) { e.printStackTrace(); } } boolean flag = gameOver(i); if (flag) { break ; } System.out.println(Thread.currentThread().getName() + "-->跑了" + i + "步" ); } } private boolean gameOver (int steps) { if (winner != null ) { return true ; } else { if (steps >= 100 ) { winner = Thread.currentThread().getName(); System.out.println("Winner is " + winner); return true ; } } return false ; } public static void main (String[] args) { Race race = new Race(); new Thread(race, "乌龟" ).start(); new Thread(race, "兔子" ).start(); } }
实现Callable 接口
实现Callable接口,需要返回值类型
重写call 方法,需要抛出异常
创建目标对象
创建执行服务:
提交执行:
获取结果:
关闭服务:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 package com.humble.callable;import com.humble.thread.TestThread2;import org.apache.commons.io.FileUtils;import java.io.File;import java.io.IOException;import java.net.URL;import java.util.concurrent.*;public class TestCallable implements Callable <Boolean > { private String url; private String name; public TestCallable (String url, String name) { this .name = name; this .url = url; } @Override public Boolean call () throws Exception { WebDownloader webDownloader = new WebDownloader(); webDownloader.downLoader(url,name); System.out.println("下载了文件名为:" +name); return true ; } public static void main (String[] args) throws ExecutionException, InterruptedException { TestCallable t1 = new TestCallable("http://192.168.1.1/tmp/a.jpg" , "1.jpg" ); TestCallable t2 = new TestCallable("http://192.168.1.1/tmp/b.jpg" , "2.jpg" ); TestCallable t3 = new TestCallable("http://192.168.1.1/tmp/c.jpg" , "3.jpg" ); ExecutorService ser = Executors.newFixedThreadPool(3 ); Future<Boolean> r1 = ser.submit(t1); Future<Boolean> r2 = ser.submit(t2); Future<Boolean> r3 = ser.submit(t3); Boolean rs1 = r1.get(); Boolean rs2 = r2.get(); Boolean rs3 = r3.get(); ser.shutdownNow(); } } class WebDownloader { public void downLoader (String url, String name) { try { FileUtils.copyURLToFile(new URL(url), new File(name)); } catch (IOException e) { e.printStackTrace(); System.out.println("IO 异常,Downloader方法出现问题" ); } } }
静态代理 静态代理总结:
真实对象和代理对象都要实现同一个接口
代理对象要代理真实角色
好处:
代理对象可以做很多对象做不了的事情
真实对象专注做自己的事情
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 package com.humble.proxy;public class StacticProxy { public static void main (String[] args) { new WeddingCompany(new You()).happyMarry(); } } interface Marry { void happyMarry () ; }class You implements Marry { @Override public void happyMarry () { System.out.println("星星要结婚了,超开心" ); } } class WeddingCompany implements Marry { private Marry target; public WeddingCompany (Marry target) { this .target = target; } @Override public void happyMarry () { before(); this .target.happyMarry(); after(); } private void after () { System.out.println("结婚之后,收尾款" ); } private void before () { System.out.println("结婚之前,布置现场" ); } }
Lambda表达式
入 希腊字母表中排序第十一位的字母,英语名称为Lambda
避免内部类定义过多
其实质属于函数式编程概念
1 2 3 4 5 (params) -> expression [表达式] (params) -> statement [语句] (params) -> { statement } new Thread(()-> System.out.println("多线程学习" )).start();
为什么要使用lambda表达式
避免你们内部类定义过多
可以让你的代码看起来很简洁
去掉了一堆没有意义的代码,只留下核心的逻辑
函数式接口(function interface)的定义
任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口。1 public interface Runnable { public abstract void run () ; }
对于函数式接口,我们可以通过lambda 表达式来创建该接口的对象。
案例1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 package com.humble.lambda;public class TestLambda { static class Like2 implements ILike { @Override public void lambda () { System.out.println(" i like lambda2" ); } } public static void main (String[] args) { ILike like = new Like(); like.lambda(); like = new Like2(); like.lambda(); class Like3 implements ILike { @Override public void lambda () { System.out.println(" i like lambda3" ); } } like = new Like3(); like.lambda(); like = new ILike() { @Override public void lambda () { System.out.println(" i like lambda4" ); } }; like.lambda(); like = ()->{ System.out.println(" i like lambda5" ); }; like.lambda(); } } interface ILike { void lambda () ; } class Like implements ILike { @Override public void lambda () { System.out.println(" i like lambda" ); } }
案例2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 package com.humble.lambda;public class TestLambda2 { public static void main (String[] args) { ILove love = null ; love = (int a,int b)->{ System.out.println("i love-" +a); }; love = (a,b)->{ System.out.println("i love-" +a); }; love = (a,b)->System.out.println("i love-" +a); love.love(520 ); } } interface ILove { void love (int a, int b) ; }
线程状态
线程停止
建议线程正常停止->利用次数。不建议死循环
建议使用标志位->设置一个标志位
stop和destory等过时方法不建议使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 package com.humble.state;public class TestStop implements Runnable { private boolean flag = true ; @Override public void run () { int i = 0 ; while (flag) { System.out.println("run...Thread->" + i++); } } public void stop () { this .flag = false ; } public static void main (String[] args) { TestStop testStop = new TestStop(); new Thread(testStop).start(); for (int i = 0 ; i < 1000 ; i++) { System.out.println("main" + i); if (i == 900 ) { testStop.stop(); System.out.println("该线程停止了" ); } } } }
1 2 3 4 5 6 7 8 9 main0 ... run...Thread->0 ... main900 run...Thread->2 该线程停止了 main901 ...
线程休眠(sleep)
sleep(时间)指定当前线程阻塞的毫秒数;
sleep 存在异常InterruptedException;
sleep 时间达到后线程进入就绪状态
sleep 可以模拟网络延时,倒计时等。
每一个对象都有一个锁,sleep不会释放锁;
案例:模拟网络延时 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 package com.humble.state;public class TestSleep implements Runnable { private int ticketNums = 10 ; @Override public void run () { while (true ) { if (ticketNums <= 0 ) { break ; } try { Thread.sleep(100 ); } catch (Exception e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "--->拿到了第" + ticketNums-- + "票" ); } } public static void main (String[] args) { TestSleep testSleep = new TestSleep(); new Thread(testSleep,"小明" ).start(); new Thread(testSleep,"小红" ).start(); new Thread(testSleep,"小黄牛" ).start(); } }
案例:模拟倒计时 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 package com.humble.state;import java.text.SimpleDateFormat;import java.util.Date;public class TestSleep2 { public static void testDown () throws InterruptedException { int num = 10 ; while (true ) { Thread.sleep(1000 ); System.out.println(num--); if (num == 0 ) { break ; } } } public static void printNowDate () { Date stattTime = new Date(System.currentTimeMillis()); while (true ) { try { Thread.sleep(1000 ); System.out.println(new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss" ).format(stattTime)); stattTime = new Date(System.currentTimeMillis()); } catch (Exception e) { e.printStackTrace(); } } } public static void main (String[] args) { printNowDate(); } }
线程礼让(yield)
礼让线程,让当前正在执行的线程暂停,但不阻塞
将线程从运行状态转为就绪状态
让cpu 重新调度,礼让不一定成功!看cpu心情
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 package com.humble.state;public class TestYield { public static void main (String[] args) { MyYield myYield = new MyYield(); new Thread(myYield,"a" ).start(); new Thread(myYield,"b" ).start(); } } class MyYield implements Runnable { @Override public void run () { System.out.println(Thread.currentThread().getName()+"执行" ); Thread.yield(); System.out.println(Thread.currentThread().getName()+"停止" ); } }
线程强制执行(join) Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞,可以想象成插队
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package com.humble.state;public class TestJoin implements Runnable { @Override public void run () { for (int i = 0 ; i < 100 ; i++) { System.out.println("线程vip来了" + i); } } public static void main (String[] args) throws InterruptedException { TestJoin testJoin = new TestJoin(); Thread thread = new Thread(testJoin); thread.start(); for (int i = 0 ; i < 200 ; i++) { if (i == 100 ) { thread.join(); } System.out.println("main" + i); } } }
1 2 3 4 5 6 7 8 9 main0 ... main99 线程vip来了0 ... 线程vip来了99 main100 ... main199
Thread.State 线程状态,线程可以处于以下状态之一:
NEW 尚未启动的线程处于此状态
RUNNABLE 在Java虚拟机中执行的线程处于此状态
BLOCKED 被阻塞等待监视器锁定的线程处于此状态
WAITING 正在等待另一个线程执行特定动作的线程处于此状态
TIMED_WAITING 正在等待另一个线程执行动作达到指定等待时间的线程处于此状态
TERMINATED 已退出的线程处于此状态
一个线程可以在给定时间点处于一个状态,这些状态不反映任何操作系统线程状态的虚拟机状态。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 package com.humble.state;public class TeestState { public static void main (String[] args) throws InterruptedException { Thread thread = new Thread(()->{ for (int i = 0 ; i < 5 ; i++) { try { Thread.sleep(1000 ); }catch (Exception e){ e.printStackTrace(); } System.out.println("/" ); } }); Thread.State state = thread.getState(); System.out.println(state); thread.start(); state = thread.getState(); System.out.println(state); while (state != Thread.State.TERMINATED){ Thread.sleep(100 ); state = thread.getState(); System.out.println(state); } } }
1 2 3 4 5 6 7 NEW RUNNABLE TIMED_WAITING ... TIMED_WAITING / TERMINATED
注意:线程中断或结束,一旦进入死亡状态,就不能再次启动。
线程优先级
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器安装优先级决定应该调度哪个线程来执行。
线程的优先级用数字表示,范围从1-101 2 3 Thread.MIN_PRIORITY = 1 ; Thread.MAX_PRIORITY = 10 ; Thread.NORM_PRIORITY = 5 ;
使用以下方式改变或获取优先级1 2 getPriority() setPriority(int xx)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 package com.humble.state;public class TestPriority { public static void main (String[] args) { System.out.println(Thread.currentThread().getName()+"==" +Thread.currentThread().getPriority()); MyPriority myPriority = new MyPriority(); Thread t1 = new Thread(myPriority); Thread t2 = new Thread(myPriority); Thread t3 = new Thread(myPriority); Thread t4 = new Thread(myPriority); Thread t5 = new Thread(myPriority); Thread t6 = new Thread(myPriority); t1.start(); t2.setPriority(1 ); t2.start(); t3.setPriority(4 ); t3.start(); t4.setPriority(Thread.MAX_PRIORITY); t4.start(); t5.setPriority(8 ); t5.start(); t6.setPriority(7 ); t6.start(); } } class MyPriority implements Runnable { @Override public void run () { System.out.println(Thread.currentThread().getName()+"==" +Thread.currentThread().getPriority()); } }
优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用,这都是看CPU的调度。
守护(daemon)线程
线程分为用户线程和守护线程
虚拟机必须确保用户线程执行完毕
虚拟机不用等待守护线程执行完毕 如:后台记录操作日志、监控内存、垃圾回收等等…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 package com.humble.state;public class TestDaemon { public static void main (String[] args) { God god = new God(); You you = new You(); Thread thread = new Thread(god); thread.setDaemon(true ); thread.start(); new Thread(you).start(); } } class You implements Runnable { @Override public void run () { for (int i = 0 ; i < 36500 ; i++) { System.out.println("你活着" ); } System.out.println("--goodbye" ); } } class God implements Runnable { @Override public void run () { while (true ) { System.out.println("上帝保护着你" ); } } }
1 2 3 4 5 6 7 8 9 你活着 上帝保护着你 ... 上帝保护着你 你活着 --goodbye 上帝保护着你 ... 上帝保护着你
线程同步 多个线程操作同一个资源
并发:同一个对象被多个线程同时操作
现实生活中,我们会遇到“同一资源,多个人都想使用”的问题,比如:食堂排队打饭,每个人都想吃饭,最天然的解决办法就是,排队。一个个来
处理多线程问题时,多个线程访问同一个对象(并发),并且某些线程还想修改这个对象,这个时候我们就需要线程同步,线程同步就是一种机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用。
队列 由于同一个进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入 锁机制 synchronized ,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可。
存在以下问题:
一个线程有锁会导致其他需要此锁的线程挂起;
在多线程竞争下,加锁,释放锁会导致比较多的上下文切换 和 调度延时,引起性能问题;
如果一个优先级高的线程等待一个优先级低的线程释放锁 会导致优先级倒置,引起性能问题。
3大线程案例 线程案例1:不安全的买票 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 package com.humble.syn;public class UnsafeBuyTicket { public static void main (String[] args) { BuyTicket station = new BuyTicket(); new Thread(station,"你" ).start(); new Thread(station,"我" ).start(); new Thread(station,"他" ).start(); } } class BuyTicket implements Runnable { private int ticketNums = 10 ; private boolean flag = true ; @Override public void run () { while (flag) { buy(); } } private void buy () { if (ticketNums <= 0 ) { flag = false ; return ; } try { Thread.sleep(100 ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "拿到第" + ticketNums-- + "张票" ); } }
1 2 3 4 5 6 7 8 9 10 11 你拿到第10张票 他拿到第9张票 你拿到第8张票 我拿到第7张票 他拿到第6张票 你拿到第5张票 我拿到第4张票 你拿到第3张票 我拿到第2张票 他拿到第1张票 我拿到第-1张票 //线程不安全,有-1
线程案例2:不安全的取钱 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 package com.humble.syn;public class UnsafeBank { public static void main (String[] args) { Account account = new Account(100 , "结婚基金" ); Drawing you = new Drawing(account,50 ,"你" ); Drawing girlFriend = new Drawing(account,100 ,"girlFriend" ); you.start(); girlFriend.start(); } } class Account { int money; String name; public Account (int money, String name) { this .money = money; this .name = name; } } class Drawing extends Thread { Account account; int drawingMoney; int nowMoney; public Drawing (Account account, int drawingMoney, String name) { super (name); this .account = account; this .drawingMoney = drawingMoney; } @Override public void run () { if (account.money - drawingMoney < 0 ) { System.out.println(Thread.currentThread().getName() + "钱不够,取不了" ); return ; } try { Thread.sleep(100 ); } catch (InterruptedException e) { e.printStackTrace(); } account.money = account.money - drawingMoney; nowMoney = nowMoney + drawingMoney; System.out.println(account.name + "余额为:" + account.money); System.out.println(this .getName() + "手里的钱" + nowMoney); } }
1 2 3 4 结婚基金余额为:50 你手里的钱:50 结婚基金余额为:-50 girlFriend手里的钱:100
线程案例3:不安全的集合 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 package com.humble.syn;import java.util.ArrayList;import java.util.List;public class UnsafeList { public static void main (String[] args) throws InterruptedException { List<String> list = new ArrayList<>(); for (int i = 0 ; i < 10000 ; i++) { new Thread(()->{ list.add(Thread.currentThread().getName()); }).start(); } try { Thread.sleep(3000 ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(list.size()); } }
线程同步 同步方法 由于我们可以通过private 关键字来保证数据对象只能被方法访问,所以我们只需要对方法提出一套机制,这套机制就是synchronized 关键字,它包括两种用法:synchronized 方法和synchronized 块;
1 public synchronized void method (int args) {}
synchronized 方法 控制对 “对象”的访问,每个对象对应一把锁,每个synchronized 方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。
缺陷:若将一个大的方法声明为synchronized 将会影响效率。
方法里面需要修改的内容才需要锁,锁的太多,浪费资源。
完善不安全的买票 1 private synchronized void buy () {
1 2 3 4 5 6 7 8 9 10 你拿到第10张票 他拿到第9张票 你拿到第8张票 我拿到第7张票 他拿到第6张票 你拿到第5张票 我拿到第4张票 你拿到第3张票 我拿到第2张票 他拿到第1张票 //没有出现-1了
同步块
obj 称之为 同步监视器 obj 可以是任何对象,但是推荐使用共享资源作为同步监视器 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是和这个对象本身,或者是class
同步监视器的执行过程
第一个线程访问,锁定同步监视器,执行其中代码
第二个线程访问,发现同步监视器,无法访问
第一个线程访问完毕,解锁同步监视器
第二个线程访问,发现同步监视器没有锁,然后锁定并访问
锁的对象就是变化的量,需要增删改的数据
完善不安全的取钱 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public void run () { synchronized (account) { if (account.money - drawingMoney < 0 ) { System.out.println(Thread.currentThread().getName() + "钱不够,取不了" ); return ; } try { Thread.sleep(100 ); } catch (InterruptedException e) { e.printStackTrace(); } account.money = account.money - drawingMoney; nowMoney = nowMoney + drawingMoney; System.out.println(account.name + "余额为:" + account.money); System.out.println(this .getName() + "手里的钱" + nowMoney); } }
1 2 3 结婚基金余额为:50 你手里的钱:50 girlFriend钱不够,取不了
完善不安全的集合 1 2 3 4 5 6 new Thread(()->{ synchronized (list){ list.add(Thread.currentThread().getName()); } }).start();
JUC并发编程 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package com.humble.syn;import java.util.concurrent.CopyOnWriteArrayList;public class TestJUC extends Thread { public static void main (String[] args) { CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>(); for (int i = 1 ; i < 10000 ; i++) { new Thread(()->{ list.add(Thread.currentThread().getName()); }).start(); } try { Thread.sleep(3000 ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(list.size()); } }
死锁 多个线程互相抱着对象需要的资源,然后形成僵持。
多个线程各自占有一些资源,并且互相等待其他线程占有的资源才能运行,而导致这两个或者多个线程都在等待对方释放资源,都停止执行的情形,某一个同步块同时拥有“两个以上对象的锁时”,就可能发生“死锁”的问题。
死锁案例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 package com.humble.thread;public class TestLock { public static void main (String[] args) { Makeup g1 = new Makeup(0 ,"灰姑凉" ); Makeup g2 = new Makeup(1 ,"白雪公主" ); g1.start(); g2.start(); } } class Lipstick { } class Mirror { } class Makeup extends Thread { static Lipstick lipstick = new Lipstick(); static Mirror mirror = new Mirror(); int choice; String girlName; public Makeup (int choice, String girlName) { this .choice = choice; this .girlName = girlName; } @Override public void run () { try { makeup(); } catch (InterruptedException e) { e.printStackTrace(); } } private void makeup () throws InterruptedException { if (choice == 0 ) { synchronized (lipstick) { System.out.println(this .girlName + "获得口红的锁" ); Threadksleep(100 ); synchronized (mirror) { System.out.println(this .girlName + "获得镜子的锁" ); } } } else { synchronized (mirror) { System.out.println(this .girlName + "获得镜子的锁" ); Thread.sleep(100 ); synchronized (lipstick) { System.out.println(this .girlName + "获得口红的锁" ); } } } } }
完善
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 private void makeup () throws InterruptedException { if (choice == 0 ) { synchronized (lipstick) { System.out.println(this .girlName + "获得口红的锁" ); Threadksleep(100 ); } synchronized (mirror) { System.out.println(this .girlName + "获得镜子的锁" ); } } else { synchronized (mirror) { System.out.println(this .girlName + "获得镜子的锁" ); Thread.sleep(100 ); } synchronized (lipstick) { System.out.println(this .girlName + "获得口红的锁" ); } } }
1 2 3 4 灰姑娘获得口红的锁 白雪公主获得镜子的锁 白雪公主获得口红的锁 灰姑娘获得镜子的锁
产生死锁的四个必要条件:
互斥条件:一个资源每次只能被一个进程使用。
请求与保持条件:一个进程因请求资源而阻塞,对已获得的资源保持不放。
不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺。
循环等待条件:若干个进程之间形成一种头尾相接的循环等待资源关系。
Lock(锁) 可重入锁
从JDK 5.0开始,Java提供了更强大的线程同步机制——通过显式定义同步锁对象来实现同步。同步锁使用Lock对象充当
java.util.concurrent.locks.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象。
ReentrantLock 类实现了Lock,它拥有与 synchronized 相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显式加锁、释放锁。
lock锁案例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 package com.humble.gaoji;import java.util.concurrent.locks.ReentrantLock;public class TestLock { public static void main (String[] args) { TestLock2 lock2 = new TestLock2(); new Thread(lock2,"你" ).start(); new Thread(lock2,"我" ).start(); new Thread(lock2,"他" ).start(); } } class TestLock2 implements Runnable { int ticketNums = 10 ; private final ReentrantLock lock = new ReentrantLock(); @Override public void run () { while (true ){ try { lock.lock(); if (ticketNums >0 ){ try { Thread.sleep(100 ); }catch (Exception e){ e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+" " +ticketNums--); }else { break ; } }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); } } } }
Synchronized vs Lock
Lock是显式锁(手动开启和关闭锁,别忘记关闭锁) synchronized是隐式锁,出了作用域自动释放
Lock只有代码块锁,synchronized有代码块锁和方法锁
使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)
优先使用顺序: Lock > 同步代码块 (已经进入了方法体,分配相应资源) > 同步方法(在方法体之外)
线程通信问题 生产者和消费者问题
假设仓库中只能存放一件产品,生产者将生产出来的产品放入仓库﹐消费者将仓库中产品取走消费。
如果仓库中没有产品﹐则生产者将产品放入仓库﹐否则停止生产并等待,直到仓库中的产品被消费者取走为止。
如果仓库中放有产品,则消费者可以将产品取走消费﹐否则停止消费并等待,直到仓库再次放入产品为止。
这是一个线程同步问题,生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件。
对于生产者﹐没有生产产品之前,要通知消费者等待﹒而生产了产品之后﹐又需要马上通知消费者消费
对于消费者﹐在消费之后﹐要通知生产者已经结束消费﹐需要生产新的产品以供消费.
在生产者消费者问题中,仅有synchronized是不够的 synchronized可阻止并发更新同一个共享资源,实现了同步 synchronized不能用来实现不同线程之间的消息传递(通信)
Java提供了几个方法解决线程之间的通信问题
注意:均是Object类 的方法,都只能在同步方法或者同步代码块中使用,否则会抛出lllegalMonitorStateException
解决方式1 并发协作模型“生产者/消费者模式”->管程法
生产者:负责生产数据的模块(可能是方法,对象,线程,进程)
消费者:负责处理数据的模块(可能是方法,对象,线程,进程)
缓冲区:消费者不能直接使用生产者的数据﹐他们之间有个“缓冲区
生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 package com.humble.gaoji;public class TestPC { public static void main (String[] args) { SynContainer container = new SynContainer(); new Productor(container).start(); new Consumer(container).start(); } } class Productor extends Thread { SynContainer container; public Productor (SynContainer container) { this .container = container; } @Override public void run () { for (int i = 1 ; i <= 20 ; i++) { container.push(new Chiken(i)); System.out.println("生产了" +i+"只鸡" ); } } } class Consumer extends Thread { SynContainer container; public Consumer (SynContainer container) { this .container = container; } @Override public void run () { for (int i = 1 ; i <= 20 ; i++) { Chiken pop = container.pop(); System.out.println("消费了第" +pop.id+"只鸡" ); } } } class Chiken { int id; public Chiken (int id) { this .id = id; } } class SynContainer { Chiken[] chikens = new Chiken[10 ]; int count = 0 ; public synchronized void push (Chiken chiken) { if (count == chikens.length) { try { this .wait(); } catch (InterruptedException e) { e.printStackTrace(); } } chikens[count] = chiken; count++; this .notifyAll(); } public synchronized Chiken pop () { if (count == 0 ) { try { this .wait(); } catch (InterruptedException e) { e.printStackTrace(); } } count--; Chiken chiken = chikens[count]; this .notifyAll(); return chiken; } }
解决方式2 并发协作模型“生产者/消费者模式”->信号灯法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 package com.humble.gaoji;public class TestPC2 { public static void main (String[] args) { TV tv = new TV(); new Player(tv).start(); new Watcher(tv).start(); } } class Player extends Thread { TV tv; public Player (TV tv) { this .tv = tv; } @Override public void run () { for (int i = 1 ; i <= 20 ; i++) { if (i%2 == 0 ){ this .tv.play("真还传" ); } else { this .tv.play("广告" ); } } } } class Watcher extends Thread { TV tv; public Watcher (TV tv) { this .tv = tv; } @Override public void run () { for (int i = 1 ; i <= 20 ; i++) { this .tv.watch(); } } } class TV { String voice; boolean flag = true ; public synchronized void play (String voice) { if (!flag) { try { this .wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("演员表演了:" +voice); this .voice = voice; this .flag = !this .flag; this .notifyAll(); } public synchronized void watch () { if (flag) { try { this .wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("观众观看了:" +voice); this .flag = !this .flag; this .notifyAll(); } }
1 2 3 4 5 6 演员表演了:真还传 观众观看了:真还传 演员表演了:广告 观众观看了:广告 演员表演了:真还传 ...
线程池 背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
思路︰提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具。
好处:
提高响应速度(减少了创建新线程的时间)
降低资源消耗(重复利用线程池中线程,不需要每次都创建)
便于线程管理(…)
1 2 3 corePoolSize:核心池的大小 maximumPoolSize:最大线程数 keepAliveTime:线程没有任务时最多保持多长时间后会终止
JDK 5.0起提供了线程池相关API:
ExecutorService和Executors ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor
void execute(Runnable cgmmand):执行任务/命令,没有返回值,一般用来执行Runnable
Future submit(Callable task):执行任务,有返回值,一般又来执行Callable
void shutdown():关闭连接池
Executors: 工具类、线程池的工厂类,用于创建并返回不同类型的线程池
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 package com.humble.gaoji;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class TestPool { public static void main (String[] args) { ExecutorService service = Executors.newFixedThreadPool(10 ); service.execute(new MyThread()); service.execute(new MyThread()); service.execute(new MyThread()); service.execute(new MyThread()); service.shutdown(); } } class MyThread implements Runnable { @Override public void run () { System.out.println(Thread.currentThread().getName()); } }