多线程
程序:指令和数据的有序集合,本身没有运行的含义,是静态的概念
进程(Process):执行程序的一次执行过程,是一个动态的概念,是系统资源分配的单位
线程(Thread):通常一个进程中可以包含若干个线程,一个进程中至少有一个线程,不然没有存在的意义。线程是CPU调度和执行的单位
注意:很多多线程都是模拟出来的,真正的多线程是有多个CPU,即多核,如服务器。若干是模拟出来的多线程,即在一个CPU的情况下,同一时间点,CPU只能执行一个代码,因为切换得很快,所以会有同时执行的错觉
核心概念
- 线程就是独立的执行路径
- 在程序运行时,即使没有自己创建线程,后台也会有多个线程,如主线程,gc线程
- mian()称之为主线程,为系统的入口,用于执行整个程序
- 在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调度,调度器是与操作系统紧密相关的,先后顺序是不能人为干预的
- 对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制
- 线程会带来额外的开销,如cpu调度时间,并发控制开销
- 每个线程在自己的工作内存交互,内存控制不当会造成数据的不一致
线程创建
三种创建方式
-
Thread class : 继承Thread类(重点)
**Runnable接口 ** : 实现Runnable接口(重点)(推荐使用)
Callable接口 : 实现Callable接口
-
继承Thread类
- 子类继承Thread类具备多线程能力
- 重写run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
package thread.demo01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//练习Thread,实现多线程同步下载文件
public class TestThread02 extends Thread{
private String url; //网络图片地址
private String name; //保存的文件名
public TestThread02(String url,String name){
this.url = url;
this.name = name;
}
//下载图片线程的执行体
@Override
public void run() {
WebDownLoader webDownLoader = new WebDownLoader();
webDownLoader.downLoader(url,name);
System.out.println("下载了文件名为:"+name);
}
public static void main(String[] args) {
TestThread02 testThread01 = new TestThread02("https://rs1.huanqiucdn.cn/dp/api/images/imageDir/e9add2f801a36694cd6852dbd3eea4b6.jpg","1.jpg");
TestThread02 testThread02 = new TestThread02("https://uploadfile.bizhizu.cn/up/11/22/8d/11228db3de753f335c1f1aceedaaebb0.jpg","2.jpg");
TestThread02 testThread03 = new TestThread02("https://p9.itc.cn/images01/20210120/0482c4bcff9d432890071b9f9cd3b3c4.jpeg","3.jpg");
testThread01.start();
testThread02.start();
testThread03.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方法出现问题");
}
}
}
- 实现Runnable接口
- 实现Runnable接口具备多线程能力
- 实现run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
package thread.demo01;
//创建线程方式二:实现Runnable接口,重写run方法,执行线程需要丢入的Runnable接口接口实现类,调用start()方法
public class TestThread03 implements Runnable{
public static void main(String[] args) {
//创建一个线程对象
TestThread03 testThread03 = new TestThread03();
//使用start()方法开启线程
new Thread(testThread03).start();
for (int i = 0; i < 1000; i++) {
System.out.println("黄格燕崽崽");
}
}
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("曾成进崽崽奴");
}
}
}
package thread.demo01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//继承Runnable接口,实现多线程同步下载文件
public class TestThread02 implements Runnable{
private String url; //网络图片地址
private String name; //保存的文件名
public TestThread02(String url,String name){
this.url = url;
this.name = name;
}
//下载图片线程的执行体
@Override
public void run() {
WebDownLoader webDownLoader = new WebDownLoader();
webDownLoader.downLoader(url,name);
System.out.println("下载了文件名为:"+name);
}
public static void main(String[] args) {
TestThread02 testThread01 = new TestThread02("https://rs1.huanqiucdn.cn/dp/api/images/imageDir/e9add2f801a36694cd6852dbd3eea4b6.jpg","1.jpg");
TestThread02 testThread02 = new TestThread02("https://uploadfile.bizhizu.cn/up/11/22/8d/11228db3de753f335c1f1aceedaaebb0.jpg","2.jpg");
TestThread02 testThread03 = new TestThread02("https://p9.itc.cn/images01/20210120/0482c4bcff9d432890071b9f9cd3b3c4.jpeg","3.jpg");
new Thread(testThread01).start();
new Thread(testThread02).start();
new Thread(testThread03).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方法出现问题");
}
}
}
初识并发问题
package thread.demo01;
//多个线程同时操作同一个对象
//买火车票的例子
//发现问题:多个线程同时操作同一个对象的时候,线程不安全,数据紊乱
public class TestThread04 implements Runnable{
private int ticketNums = 10;
@Override
public void run() {
while (true){
if (ticketNums<=0){
break;
}
//模拟延时
System.out.println(Thread.currentThread().getName()+"抢到了第"+ticketNums--+"张票");
}
}
public static void main(String[] args) {
TestThread04 testThread04 = new TestThread04();
new Thread(testThread04,"黄格燕").start();
new Thread(testThread04,"黄锦燕").start();
new Thread(testThread04,"黄佳权").start();
}
}
龟兔赛跑
package thread.demo01;
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%80==0){
try {
Thread.sleep(1);
} 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();
}
}
静态代理模式
package thread.demo02;
//静态代理模式总结
//真实对象和代理对象都要实现同一个接口
//代理对象要代理真实角色
//好处:
//代理对象可以做很多真实对象做不了的事情
//真实对象专注做自己的事情
public class StaticProxy {
public static void main(String[] args) {
You you = new You();
WeddingCompany weddingCompany = new WeddingCompany(you);
weddingCompany.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("结婚前");
}
}
Lamda表达式
函数式接口:一个接口里只有一个方法
package thread.demo02;
public class TestLambda {
public static void main(String[] args) {
ILike like = new Like();
like.lambda();
like = new Like2();
like.lambda();
//4:局部内部类
class Like3 implements ILike{
@Override
public void lambda() {
System.out.println("I like lambda3");
}
}
like = new Like3();
like.lambda();
//5:匿名内部类:没有名字的类,必须借助接口或者父类
like = new ILike() {
@Override
public void lambda() {
System.out.println("I like lambda4");
}
};
like.lambda();
//6:用lambda简化
like = ()->{
System.out.println("I like lambda5");
};
like.lambda();
}
}
//1:定义一个函数式接口
interface ILike{
void lambda();
}
//2:实现类
class Like implements ILike{
@Override
public void lambda() {
System.out.println("I like lambda1");
}
}
//3:静态内部类
static class Like2 implements ILike{
@Override
public void lambda() {
System.out.println("I like lambda2");
}
}
package thread.demo02;
public class TestLambda2 {
public static void main(String[] args) {
ILove love = null;
//lambda表达式简化
/*love = (a)->{
System.out.println("I love you-->"+a);
};
//简化一:参数类型
love = (a)->{
System.out.println("I love you-->"+a);
};
//简化二:简化括号
love = a->{
System.out.println("I love you-->"+a);
};
*/
//简化三:去掉花括号
love = a-> System.out.println("I love you-->"+a);
//总结:
//lambda表达式只能有一行代码的情况下才能简化成简化三,如果有多行,那么就用简化二
//前提是接口是函数式接口
//多个参数也可以去掉参数类型,要去掉就都去掉,必须加括号,
//一般用简化二最好
love.love("黄格燕");
}
}
interface ILove{
void love(String a);
}
线程五大状态
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XCWSwOwA-1638702491526)(C:\Users\ZCJ\Desktop\截图\QQ图片20211120191532.png)]
线程停止
package thread.demo03;
//测试stop
//1.建议线程正常停止,利用次数,不建议死循环
//2.建议使用标志位,设置一个标志位
//3.不要使用stop或者destroy等过时或者JDK不建议的方法
public class TestStop implements Runnable{
private boolean flag = true;
@Override
public void run() {
while (flag){
System.out.println("滴滴滴,线程执行,滴滴滴");
}
}
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 <= 20; i++) {
System.out.println("main方法执行" + i);
if(i == 15){
testStop.stop();
System.out.println("线程停止执行");
}
}
}
}
线程休眠
- sleep指定当前线程阻塞的时间
- sleep存在异常InterruptedException;
- sleep时间达到后线程进入就绪状态
- sleep可以模拟网络延时,倒计时等
- 每一个对象都有一把锁,sleep不会释放锁
package thread.demo03;
public class TestSleep implements Runnable {
//模拟网络问题,放大问题发生性
private int ticket = 10;
@Override
public void run() {
while (true){
if (ticket <= 0){
break;
}
//模拟延时
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"抢到了第"+ticket--+"张票");
}
}
public static void main(String[] args) {
TestSleep testSleep1 = new TestSleep();
new Thread(testSleep1,"小奶").start();
new Thread(testSleep1,"中奶").start();
new Thread(testSleep1,"大奶").start();
}
}
package thread.demo03;
public class TestSleep2 {
public static void main(String[] args) throws InterruptedException {
tenDown();
}
//模拟倒计时
public static void tenDown() throws InterruptedException {
int time = 10;
while (true){
Thread.sleep(1000);
System.out.println(time);
time--;
if (time < 0){
break;
}
}
}
}
/*
//打印当前系统时间
public static void main(String[] args) {
//获取当前系统时间
Date date = new Date(System.currentTimeMillis());
while (true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
date = new Date(System.currentTimeMillis());//更新当前时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
*/
线程礼让
package thread.demo03;
//礼让线程,让当前正在执行的线程暂停,但不阻塞
//将线程从运行状态转为就绪状态
//礼让cpu重新调度,礼让不一定成功,看CPU心情
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
package thread.demo03;
//Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
//可以想象成插队
public class TestJoin implements Runnable{
public static void main(String[] args) throws InterruptedException {
//启动线程
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
//主线程
for (int i = 0; i < 1000; i++) {
if (i == 200){
thread.join();//插队
}
System.out.println("main"+i);
}
}
@Override
public void run() {
for (int i = 0; i <= 400; i++) {
System.out.println("线程vip来了" + i);
}
}
}
线程状态监测
package thread.demo03;
public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("");
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state);//NEW状态
//观察启动后
thread.start();//启动线程
state = thread.getState();
System.out.println(state);//RUN状态
//运行时状态
while (state != Thread.State.TERMINATED){//只要线程不终止,就一直输出状态
Thread.sleep(100);
state = thread.getState();
System.out.println(state);
}
}
}
线程优先级
package thread.demo03;
public class TestPriority {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread thread1 = new Thread(myPriority);
Thread thread2 = new Thread(myPriority);
Thread thread3 = new Thread(myPriority);
Thread thread4 = new Thread(myPriority);
Thread thread5 = new Thread(myPriority);
//先设置优先级再启动
thread1.start();
thread2.setPriority(3);
thread2.start();
thread3.setPriority(Thread.MIN_PRIORITY);//MIN_PRIORITY = 1
thread3.start();
thread4.setPriority(6);
thread4.start();
thread5.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY = 10
thread5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
守护(daemon)线程
-
是一个布尔值
-
线程分为用户线程和守护线程
-
虚拟机必须确保用户线程执行完毕
-
虚拟机不用等守护线程执行完毕
package thread.demo03;
import java.sql.SQLOutput;
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 God implements Runnable{
@Override
public void run() {
while (true){
System.out.println("黄格燕一直爱着你!");
}
}
}
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 3650; i++) {
System.out.println("好好生活!");
}
System.out.println("============Everything will up;");
}
}
线程同步机制
- 并发:同一个对象被多个线程同时使用
- 处理多线程问题时,多个线程访问一个对象,并且某些线程还想修改这个对象,这时候我们就需要线程同步,线程同步其实就是一种等待机制,多个需要同时访问对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用
- 线程同步形成条件:队列+锁
- 由于同一进程的多个线程共享同一块储存空间,在带来方便的同时,也带来了访问冲突的问题,为了保证数据在方法中被访问的正确性,在访问时加入了锁机制synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放即可,但是也存在以下问题:
- 一个线程持有锁会导致其他需要此锁的线程挂起;
- 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题;
- 如果一个优先级高的线程等待一个优先级低的线程释放锁,会导致倒置,引起性能问题
三大不安全案例
package thread.syn;
//不安全的买票
//线程不安全
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"老鼠").start();
new Thread(buyTicket,"兔子").start();
new Thread(buyTicket,"黄牛党").start();
}
}
class BuyTicket implements Runnable{
private int ticket = 10;
boolean flag = true;
@Override
public void run() {
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException {
if (ticket <= 0){
flag = false;
return;
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticket--+"张票");
Thread.sleep(100);
}
}
package thread.syn;
//不安全的取钱
//两个人去银行取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(1000, "买房的钱");
Drawing d1 = new Drawing(account, 800, "那男的");
Drawing d2 = new Drawing(account, 400, "那女的");
d1.start();
d2.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;
}
//sleep可以放大问题的发生性
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(Thread.currentThread().getName() + "身上的钱:" + nowMoney);
}
}
package thread.syn;
import java.util.ArrayList;
import java.util.List;
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
同步方法及同步块
同步方法
- public synchronized void method(int args){}
- synchronized方法控制对"对象"的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行
- 缺陷:若将一个大的方法申明为synchronized将会影响效率
同步块
- synchronized(Obj){}
- Obj称为同步监视器
- Obj可以是任何对象,但是推荐使用共享资源作为同步监视器
- 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class
- 同步监视器的执行过程
- 第一个线程访问,锁定同步监视器,执行其中代码
- 第二个线程访问,发现同步监视器被锁定,无法访问
- 第一个线程访问完毕,解锁同步监视器
- 第二个线程访问,发现同步监视器没有被锁,然后锁定并访问
package thread.syn;
//不安全的买票
//线程不安全
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"老鼠").start();
new Thread(buyTicket,"兔子").start();
new Thread(buyTicket,"黄牛党").start();
}
}
class BuyTicket implements Runnable{
private int ticket = 10;
boolean flag = true;
@Override
public void run() {
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void buy() throws InterruptedException {
if (ticket <= 0){
flag = false;
return;
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticket--+"张票");
Thread.sleep(100);
}
}
package thread.syn;
//不安全的取钱
//两个人去银行取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(1000, "买房的钱");
Drawing d1 = new Drawing(account, 800, "那男的");
Drawing d2 = new Drawing(account, 400, "那女的");
d1.start();
d2.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() {
synchronized (account){
if (account.money - drawingMoney < 0){
System.out.println(Thread.currentThread().getName() + "取不到钱了,钱不够");
return;
}
//sleep可以放大问题的发生性
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(Thread.currentThread().getName() + "身上的钱:" + nowMoney);
}
//判断有没有钱
}
}
package thread.syn;
import java.util.ArrayList;
import java.util.List;
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
测试JUC安全类型的集合
package thread.syn;
import java.util.concurrent.CopyOnWriteArrayList;
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
死锁
- 多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形。某一个同步块同时拥有**“两个对象以上的锁”**时,就可能会发生“死锁”的问题
- 产生死锁的四个必要条件
- 互斥条件:一个资源每次只能被一个进程使用
- 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
- 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺
- 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
上面列出死锁的四个必要条件,我们只要想办法破其中任意一个或多个条件就可以避免死锁发生
package thread.demo04;
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
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来保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;//选择
String girlName;//使用化妆品的人
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 + "获得口红的锁");
Thread.sleep(1000);
}
synchronized (mirror){//获得镜子的锁
System.out.println(this.girlName + "获得镜子的锁");
}
}else {
synchronized (mirror){//获得镜子的锁
System.out.println(this.girlName + "获得镜子的锁");
Thread.sleep(2000);
}
synchronized (lipstick){//获得口红的锁
System.out.println(this.girlName + "获得口红的锁");
}
}
}
}
Lock
package thread.demo04;
import com.sun.org.apache.bcel.internal.generic.NEW;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class TestLock2 implements Runnable{
int ticketNums = 10;
//定义lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
lock.lock();//加锁
if (ticketNums > 0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}else {
break;
}
}finally {
lock.unlock();
}
}
}
}
synchronized与Lock的对比
-
Lock是显示锁(手动开启和关闭锁,别忘记关闭锁)synchronized是隐式锁,出了作用域自动释放
-
Lock只有代码块锁,synchronized有代码块锁和方法锁
-
使用Lock锁,JVM将花费更少的时间来调度线程,性能更好,并且具有更好的扩展性(提供更多的子类)
-
优先使用顺序
Lock > 同步代码块(已经进入了方法体,分配了相应资源)>同步方法(在方法体之外)
生产者消费者模型
解决方式一:管程法
- 生产者:负责生产数据的模块
- 消费者:负责处理数据的模块
- 缓冲区:消费者不能直接使用生产者的数据,它们之间有个“缓冲区”
- 生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据
package thread.demo04;
//测试:生产者消费者模型,利用缓冲区解决:管程法
//生产者、消费者、产品、缓冲区
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 = 0; i < 100; i++) {
container.push(new Chicken(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 = 0; i < 100; i++) {
System.out.println("消费了"+container.pop().id+"只鸡");
}
}
}
//产品
class Chicken{
int id;
public Chicken(int id) {
this.id = id;
}
}
//缓冲区
class SynContainer{
//需要一个容器大小
Chicken[] chickens = new Chicken[10];
//容器计数器
int count = 0;
//生产者放入产品
public synchronized void push(Chicken chicken){
//如果容器满了,就需要等待消费者消费
if (count == chickens.length){
//通知消费者消费,生产等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果容器没满,就需要丢入产品
chickens[count] = chicken;
count++;
//可以通知消费者消费了
this.notifyAll();
}
//消费者消费产品
public synchronized Chicken pop(){
//判断能否消费
if (count==0){
//等待生产者生产,消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//吃完了,通知生产者生产
this.notifyAll();
return chicken;
}
}
线程池
- 背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大
- 思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中,可以避免频繁创建 销毁、实现重复利用
- 好处:
- 提高响应效率(减少创建新线程的时间)
- 降低资源消耗(重复利用线程池中的线程,不需要每次都创建)
- 使用线程管理
- 线程池相关的API:ExecutorService和Executors
- ExecutorService:真正的线程池接口。常见子类:THreadPoolExecutor
- void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
- Futruesubmit(Callabletask):执行任务,有返回值,一般用来执行Callable
- void shutdown():关闭连接池
- Executor:工具类,线程池的工厂类,用于创建并返回不同类型的线程池
package thread.demo04;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestPool {
public static void main(String[] args) {
//创建服务,创建线程池
//newFixedThreadPool 参数为:线程池大小
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());
}
}
回顾
package thread.demo04;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//回顾总结线程的创建
public class ThreadNew {
public static void main(String[] args) {
new MyThread1().start();
new Thread(new MyThread2()).start();
FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3());
new Thread(futureTask).start();
try {
Integer integer = futureTask.get();
System.out.println(integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
//1.继承Thread类
class MyThread1 extends Thread{
@Override
public void run() {
System.out.println("MyThread1");
}
}
//2.实现Runnable接口
class MyThread2 implements Runnable{
@Override
public void run() {
System.out.println("MyThread2");
}
}
//3.实现callable接口
class MyThread3 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("MyThread3");
return 100;
}
}