Java多线程目录
线程简介
程序:程序是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念。
进程:进程是执行程序的一次执行过程,它是一个动态的概念。是系统资源分配的单位。
线程:线程是CPU调度和执行的单位。一个进程中可以包含若干个线程,一个进程中至少有一个线程。
核心概念
- 线程就是独立的执行路径。
- 在程序运行时,即使没有自己创建线程,后台也会有多个线程,如主线程, gc线程,main()称之为主线程,为系统的入口,用于执行整个程序。
- 在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调度,调度器是与操作系统紧密相关的,先后顺序是不能人为的干预的。
- 对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制。
- 线程会带来额外的开销,如cpu调度时间,并发控制开销。
- 每个线程在自己的工作内存交互,内存控制不当会造成数据不一致。
线程创建(重点)
继承Treated类(重点)
/**
* 1.继承Thread类
* 2.重写run()方法
* 3.调用start开启线程
*/
public class TestThread extends Thread{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 100; i++) {
System.out.println("run方法:" + i);
}
}
public static void main(String[] args) {
//main(),主线程
//创建一个线程对象
TestThread testThread = new TestThread();
//调用start() 方法开启线程
testThread.start();
for (int i = 0; i < 100; i++) {
System.out.println("main方法:" + i);
}
}
}
执行结果
main方法:0
run方法:0
main方法:1
run方法:1
main方法:2
main方法:3
run方法:2
实例分析:下载图片
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class TestThread extends Thread{
private String url; //网路图片地址
private String name; //保存的文件名
public TestThread(String url, String name) {
this.url = url;
this.name = name;
}
//下载图片线程的执行体
@Override
public void run() {
WebDownloader webDownloader = new WebDownloader();
try {
webDownloader.downloader(url,name);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("下载了文件名为:" + name);
}
public static void main(String[] arge) {
TestThread testThread1 = new TestThread("https://kuangstudy.oss-cn-beijing.aliyuncs.com/bbs/2021/06/18/kuangstudya7c810b9-c184-45fc-9f66-73bdf12db34c.png","1.jpg");
TestThread testThread2 = new TestThread("https://kuangstudy.oss-cn-beijing.aliyuncs.com/bbs/2021/04/28/kuangstudy64a54e27-7e96-4b9f-9fdc-4398a7b39eef.png","2.jpg");
TestThread testThread3 = new TestThread("https://kuangstudy.oss-cn-beijing.aliyuncs.com/bbs/2021/04/13/kuangstudy5584e809-f8cd-42c5-b8e2-cc2e69a2f9a8.png","3.jpg");
//调用start() 方法开启线程
testThread1.start();
testThread2.start();
testThread3.start();
}
}
class WebDownloader{
//下载方法
public void downloader(String url,String name) throws IOException {
FileUtils.copyURLToFile(new URL(url),new File(name));
}
}
执行结果
下载了文件名为:3.jpg
下载了文件名为:1.jpg
下载了文件名为:2.jpg
总结:
线程开启不一定立即执行,由CPU调度执行。
子类继承Thread类具备多线程能力
不建议使用:避免OOP单继承局限性
启动线程:子类对象.start()
实现Runnable接口(重点)
/**
* 1.实现runnable接口,重写run方法
* 2.执行线程需要丢入Runnable接口实现类
* 3.调用start方法
*/
public class TestThread implements Runnable{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 100; i++) {
System.out.println("run方法:" + i);
}
}
public static void main(String[] args) {
//创建runnable接口的实现类对象
TestThread testThread = new TestThread();
//创建线程对象,通过线程对象来开启我们的线程,代理
// Thread thread = new Thread(testThread);
// thread.start();
//创建线程对象并调用start方法
new Thread(testThread).start();
for (int i = 0; i < 100; i++) {
System.out.println("main方法:" + i);
}
}
}
执行结果
main方法:0
main方法:1
main方法:2
run方法:0
main方法:3
实例分析:下载图片
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class TestThread implements Runnable{
private String url; //网路图片地址
private String name; //保存的文件名
public TestThread(String url, String name) {
this.url = url;
this.name = name;
}
//下载图片线程的执行体
@Override
public void run() {
WebDownloader webDownloader = new WebDownloader();
try {
webDownloader.downloader(url,name);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("下载了文件名为:" + name);
}
public static void main(String[] arge) {
TestThread testThread1 = new TestThread("https://kuangstudy.oss-cn-beijing.aliyuncs.com/bbs/2021/06/18/kuangstudya7c810b9-c184-45fc-9f66-73bdf12db34c.png","1.jpg");
TestThread testThread2 = new TestThread("https://kuangstudy.oss-cn-beijing.aliyuncs.com/bbs/2021/04/28/kuangstudy64a54e27-7e96-4b9f-9fdc-4398a7b39eef.png","2.jpg");
TestThread testThread3 = new TestThread("https://kuangstudy.oss-cn-beijing.aliyuncs.com/bbs/2021/04/13/kuangstudy5584e809-f8cd-42c5-b8e2-cc2e69a2f9a8.png","3.jpg");
new Thread(testThread1).start();
new Thread(testThread2).start();
new Thread(testThread3).start();
}
}
class WebDownloader{
//下载方法
public void downloader(String url,String name) throws IOException {
FileUtils.copyURLToFile(new URL(url),new File(name));
}
}
执行结果
下载了文件名为:2.jpg
下载了文件名为:1.jpg
下载了文件名为:3.jpg
总结:
实现接口Runnable具有多线程能力
启动线程:传入目标对象 + Thread对象.start()
推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
//一份资源
StartThread station = new StartThread();
//多个代理
new Thread(station,name:"小明").start();
new Thread(station,name:"小红").start();
new Thread(station,name:"张三").start();
多线程操作同一个对象实例:买车票(未实现同步)
/**
* 多线程同时操作同一个对象
*/
public class TestThread01 implements Runnable{
//票数
private int ticketNum = 10;
@Override
public void run() {
while (true) {
if(ticketNum <= 0) {
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"==>获得了第" + ticketNum-- + "票");
}
}
public static void main(String[] args) {
TestThread01 thread01 = new TestThread01();
new Thread(thread01,"张三").start();
new Thread(thread01,"李四").start();
new Thread(thread01,"王二").start();
}
}
//运行结果
/*
李四==>获得了第10票
张三==>获得了第9票
王二==>获得了第8票
李四==>获得了第7票
王二==>获得了第6票
张三==>获得了第7票
李四==>获得了第5票
张三==>获得了第4票
王二==>获得了第5票
王二==>获得了第3票
李四==>获得了第1票
张三==>获得了第2票
*/
实现Callable接口(了解)
/**
* 实现Callable的好处
* 1.可以定义返回值
* 2.可以抛出异常
* 实现过程
* 1.实现Callable接口
* 2.重写call方法,需要抛出异常
* 3.创建目标对象
* 4.创建服务 ExecutorService service = Executors.newFixedThreadPool(3);
* 5.提交执行结果 Future<Boolean> submit1 = service.submit(t1);
* 6.获取结果 boolean s1 = submit1.get();
* 7.关闭服务 service.shutdownNow();
*/
public class TestCallable implements Callable<Boolean> {
private String url; //网路图片地址
private String name; //保存的文件名
public TestCallable(String url, String name) {
this.url = url;
this.name = name;
}
//下载图片线程的执行体
public Boolean call() throws IOException {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了文件名为:" + name);
return true;
}
public static void main(String[] arge) throws ExecutionException, InterruptedException {
//创建目标对象
TestCallable testThread1 = new TestCallable("https://kuangstudy.oss-cn-beijing.aliyuncs.com/bbs/2021/06/18/kuangstudya7c810b9-c184-45fc-9f66-73bdf12db34c.png","1.jpg");
TestCallable testThread2 = new TestCallable("https://kuangstudy.oss-cn-beijing.aliyuncs.com/bbs/2021/04/28/kuangstudy64a54e27-7e96-4b9f-9fdc-4398a7b39eef.png","2.jpg");
TestCallable testThread3 = new TestCallable("https://kuangstudy.oss-cn-beijing.aliyuncs.com/bbs/2021/04/13/kuangstudy5584e809-f8cd-42c5-b8e2-cc2e69a2f9a8.png","3.jpg");
//创建服务
ExecutorService service = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> submit1 = service.submit(testThread1);
Future<Boolean> submit2 = service.submit(testThread2);
Future<Boolean> submit3 = service.submit(testThread3);
//获取结果
boolean s1 = submit1.get();
boolean s2 = submit2.get();
boolean s3 = submit3.get();
//关闭服务
service.shutdownNow();
}
}
class WebDownloader{
//下载方法
public void downloader(String url,String name) throws IOException {
FileUtils.copyURLToFile(new URL(url),new File(name));
}
}
执行结果
下载了文件名为:2.jpg
下载了文件名为:1.jpg
下载了文件名为:3.jpg
静态代理模式
/**
* 静态代理总结
* 真是对象和代理对象都要实现同一个接口
* 代理对象要代理真是对象
* 优点
* 代理对象可以做很多真实对象做不了的事情
* 真实对象专注做自己的事情
*/
public class StacticProxy {
public static void main(String[] args) {
// You you = new You();//你要结婚
// WeddingCompany weddingCompany = new WeddingCompany(you);
// weddingCompany.HappyMarry(); 三行合并为一行
/* ====> */ new WeddingCompany(new You()).HappyMarry();
//同理 Thread也是代理角色,他与真实角色都实现了Runnable接口
// new Thread(()-> System.out.println("ok")).start();
}
}
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();
}
public void after() {
System.out.println("结婚后,收尾款!");
}
public void before() {
System.out.println("结婚前,布置现场!");
}
}
Lamda表达式
package com.lisicheng.JavaEE.多线程.Lamda表达式;
public class TestLamda2 {
//3.静态内部类
static class Love2 implements ILove{
@Override
public void love(int a) {
System.out.println("I love2 you ==> " + a);
}
}
public static void main(String[] args) {
Love1 love1 = new Love1();
love1.love(1);
Love2 love2 = new Love2();
love2.love(2);
//4.局部内部类
class Love3 implements ILove{
@Override
public void love(int a) {
System.out.println("I love3 you ==> " + a);
}
}
Love3 love3 = new Love3();
love3.love(3);
ILove love = null;
//5.匿名内部类
love = new ILove() {
@Override
public void love(int a) {
System.out.println("I love4 you ==> " + a);
}
};
love.love(4);
//6.lambda表达式
love = (int a)->{
System.out.println("I love5 you ==> " + a);
};
love.love(5);
//7.简化操作类型
love = (a)->{
System.out.println("I love6 you ==> " + a);
};
love.love(6);
//8.简化括号
love = a->{
System.out.println("I love7 you ==> " + a);
};
love.love(7);
//9.去掉花括号
love = a-> System.out.println("I love8 you ==> " + a);
love.love(8);
/*
总结:
1.lambda表达式只能有一行代码的情况才可以简化为一行,如果有多行,那么就用代码块包裹。
2.前提是函数式接口
3.多个参数可以去掉参数,要是去掉都去掉,否则必须加括号
*/
}
}
//1.定义一个函数式接口
interface ILove{
void love(int a);
}
//2.实现类
class Love1 implements ILove{
@Override
public void love(int a) {
System.out.println("I love1 you ==> " + a);
}
}
线程状态
线程停止
/**
* 1.建议线程正常停止 --> 利用次数,不建议死循环
* 2.建议使用标志位 --> 设置标志位
* 3.不要使用stop或者destroy等过时或者JDK官方不建议使用的方法
*/
public class TestStop implements Runnable{
//1.设置标志位
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 = 1; i <= 100; i++) {
System.out.println("main" + i);
if(i == 90) {
//调用stop方法,让线程停止
testStop.stop();
System.out.println("线程停止了!");
}
}
}
}
线程休眠
import java.text.SimpleDateFormat;
import java.util.Date;
//倒计时模拟
public class TestStop{
public static void main(String[] args) throws InterruptedException {
//模拟时间
Date date = new Date(System.currentTimeMillis());
while (true) {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
date = new Date(System.currentTimeMillis());
}
}
}
/*
//运行结果
19:11:28
19:11:29
19:11:30
19:11:31
19:11:32
*/
线程礼让
//测试礼让进程
//礼让不一定成功
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() + "--->start");
Thread.yield();
System.out.println(Thread.currentThread().getName() + "--->end");
}
}
/*
//运行结果
b--->start
a--->start
b--->end
a--->end
*/
线程插队
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) {
//启动线程
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
//主线程
for (int i = 0; i < 100; i++) {
if (i == 50) {
try {
thread.join(); //强制执行
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("main ==>" + i);
}
}
}
线程状态监测
/**
* NEW 尚未启动的线程状态
* RUNNABLE 执行中的线程状态
* BLOCKED 阻塞状态
* WAITING 线程等待
* TIMED_WAITING 线程休眠
* TERMINATED 线程结束
*/
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); //RUNNABLE
while (state != Thread.State.TERMINATED) {
Thread.sleep(100); //TIMED_WAITING等待
state = thread.getState(); //更新线程状态
System.out.println(state);//TIMED_WAITING等待
}
//观察结束后
state = thread.getState(); //更新线程状态
System.out.println(state);//TERMINATED
}
}
线程优先级
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);
//设置优先级
thread1.start(); //默认优先级 默认为5
thread2.setPriority(1);
thread2.start();
thread3.setPriority(5);
thread3.start();
thread4.setPriority(Thread.MAX_PRIORITY); //MAX_PRIORITY
thread4.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
}
}
/*
//运行结果
main-->5
Thread-3-->10
Thread-1-->1
Thread-0-->5
Thread-2-->5
*/
守护线程
- 线程分为用户线程和守护线程。
- 虚拟机必须确保用户线程执行完毕。
- 虚拟机不用等待守护线程执行完毕
- 守护线程如:后台记录操作日志,监控内存,垃圾回收等待
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); //默认为false表示是用户线程,正常的线程都是用户线程,true为守护线程
thread.start();
Thread thread1 = new Thread(you);
thread1.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 < 36500; i++) {
System.out.println("你一生都很开心");
}
System.out.println("====goodbye,world!====");
}
}
线程同步
同步:处理多线程问题时,多个线程访问同一个对象,并且某些线程还想修改这个对象。这时候我们就需要线程同步。线程同步其实就是一种等待机制 ,多个需要同时访问此对象的线程进入这个对象的等待形成队列,等待前面线程使用完毕,下一个线程再使用.
同步的实现:由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized ,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可。 存在以下问题:
- 一个线程持有锁会导致其他所有需要此锁的线程挂起。
- 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题。
- 如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题。
用法:同步块: synchronized (Obj ){ }
- Obj称之为同步监视器,Obj可以是任何对象,但是推荐使用共享资源作为同步监视器。
- 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this ,就是这个对象本身,或者是class [反射中讲解]
- synchronized默认锁的是this,因此锁的对象是变化的量,需要增删改的对象
同步监视器的执行过程:
- 第一个线程访问,锁定同步监视器,执行其中代码。
- 第二个线程访问,发现同步监视器被锁定,无法访问。
- 第一个线程访问完毕,解锁同步监视器。
- 第二个线程访问, 发现同步监视器没有锁,然后锁定并访问。
案例1:银行取款
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100,"结婚基金");
Bank you = new Bank(account,50,"You");
Bank girlFriend = new Bank(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 Bank extends Thread{
Account account;//账户
int drawingMoney;//取多少钱
int nowMoney;//现在手里的钱
public Bank(Account account,int drawingMoney,String name) {
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
// synchronized 默认锁的是this
@Override
public void run() {
//锁的对象是变化的量,需要增删改的对象
synchronized (account) {
if (account.money < drawingMoney) {
System.out.println(Thread.currentThread().getName() + "钱不够了,余额为" + account.money);
return;
}
try {
Thread.sleep(1000);
} 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);
}
}
}
加锁前:
结婚基金余额为-50
girlFriend手里的钱100
结婚基金余额为-50
You手里的钱50
加锁后:
结婚基金余额为50
You手里的钱50
girlFriend钱不够了,余额为50
案例2:火车站买票
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 ticketNum = 10;
private static boolean flag = true; //外部停止
@Override
public void run() {
//买票
while (flag) {
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// synchronized 同步方法,锁的是this
private synchronized void buy() throws InterruptedException {
//判断是否有票
if (ticketNum <= 0) {
return;
}
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName() + "拿到了-->" + ticketNum--);
}
}
加锁前:
黄牛拿到了-->5
小明拿到了-->4
张三拿到了-->3
黄牛拿到了-->2
张三拿到了-->2
小明拿到了-->2
张三拿到了-->1
黄牛拿到了-->0
小明拿到了-->-1
加锁后:
小明拿到了-->5
小明拿到了-->4
张三拿到了-->3
张三拿到了-->2
黄牛拿到了-->1
死锁
//死锁: 多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
Makeup makeup1 = new Makeup(0,"白雪公主");
Makeup makeup2 = new Makeup(1,"灰姑娘");
makeup1.start();
makeup2.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
class Makeup extends Thread {
//需要的资源只有一份,用static来保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice; //选择
String girName; //使用化妆品的人
public Makeup(int choice,String girName){
super(girName);
this.choice = choice;
this.girName = girName;
}
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void makeup() throws InterruptedException {
if (choice == 0) {
synchronized (lipstick) { //获得口红的锁
System.out.println(Thread.currentThread().getName() + "获得口红的锁");
Thread.sleep(1000);
}
synchronized (mirror) {
System.out.println(Thread.currentThread().getName() + "获得镜子的锁");
}
} else {
synchronized (mirror) { //获得镜子的锁
System.out.println(Thread.currentThread().getName() + "获得镜子的锁");
Thread.sleep(2000);
}
synchronized (lipstick) {
System.out.println(Thread.currentThread().getName() + "获得口红的锁");
}
}
}
}
/*
//运行结果
灰姑娘获得镜子的锁
白雪公主获得口红的锁
白雪公主获得镜子的锁
灰姑娘获得口红的锁
*/
总结
产生死锁的四个必要条件:
- 互斥条件:一个资源每次只能被一个进程使用。
- 请求与保持条件: -个进程因请求资源而阻塞时,对已获得的资源保持不放。
- 不剥夺条件 :进程已获得的资源,在末使用完之前,不能强行剥夺。
- 循环等待条件:若干进程之间形成-种头尾相接的循环等待资源关系。
上面列出了死锁的四个必要条件,我们只要想办法破其中的任意一个或多个条件就可以避免死锁发生。
Lock锁
/*使用方法*/
class A{
private final ReentrantLock lock = new ReenTrantLock();
public void B(){
lock.lock(); //加锁
try{
//保证线程安全
}finally{
lock.unlock(); //释放锁
}
}
}
案例:买票
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
public static void main(String[] args) {
Lock lock = new Lock();
new Thread(lock,"张三").start();
new Thread(lock,"黄牛").start();
new Thread(lock,"李四").start();
}
}
class Lock 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(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "===>" + ticketNums--);
} else break;
}finally {
lock.unlock();//释放锁
}
}
}
}
总结:synchronized与Lock的对比
-
Lock是显式锁(手动开启和关闭锁,别忘记关闭锁) synchronized是隐式锁, 出了
作用域自动释放。 -
Lock只有代码块锁synchronized有代码块锁和方法锁。
-
使甪Lock锁,JVM将花费较少的时间来调度线程(性能更好。并且具有更好的扩展性(提供更多的子类如:ReentrantLock)
-
优先使用顺序:
Lock > 同步代码块(已经进入了方法体,分配了相应资源) > 同步方法(在方法体之外)
线程通信
为什么需要线程通信?
通信的目的是为了更好的协作,线程无论是交替式执行,还是接力式执行,都需要进行通信告知。
管程法:
- wait() 表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁。
- wait(long timeout) 指定等待时间。
- notify() 唤醒一个处于等待状态的线程
- nottifyAll() 唤醒同一个对象上所有调用wait()方法的线程,优先级别高的线程优先调度。
//测试:生产者消费者模型 --> 利用缓冲区解决: 管程法
//生产者,消费者,产品,缓冲区
public class TestPC {
public static void main(String[] args) {
SynContainer synContainer = new SynContainer();
new Productor(synContainer).start();
new Consumer(synContainer).start();
}
}
//生产者
class Productor extends Thread{
SynContainer container;
public Productor(SynContainer container) {
this.container = container;
}
@Override
public void run() {
for (int i = 1; i <= 100 ; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
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 = 1; i <= 100 ; i++) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
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();//表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满,生产者需要放入产品
chickens[count] = chicken;
count++;
// System.out.println(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;
}
}
信号灯法:
//测试生产者与消费者:信号灯法,标志位解决
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 = 0; 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 = 0; i < 20; i++) {
tv.watch();
}
}
}
//产品-->节目
class TV{
String voice;//表演的节目
//演员表演,观众等待 为T
//观众观看,演员等待 为F
boolean flag = true;
//表演
public synchronized void play(String voice) {
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演" + voice);
//通知观众观看
this.notifyAll();//等待唤醒
this.voice = voice;
this.flag = !this.flag;
}
//观看
public synchronized void watch() {
if(flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了:" + voice);
//通知演员表演
this.notifyAll();
this.flag = !this.flag;
}
}
线程池
线程池的优点
- 降低系统资源消耗,通过重用已存在的线程,降低线程创建和销毁造成的消耗。
- 提高系统响应速度,当有任务到达时,通过复用已存在的线程,无需等待新线程的创建便能立即执行。
- 方便线程并发数的管控。因为线程若是无限制的创建,可能会导致内存占用过多而产生OOM,并且会造成cpu过度切换(cpu切换线程是有时间成本的(需要保持当前执行线程的现场,并恢复要执行线程的现场))。
- 提供更强大的功能,延时定时线程池。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//测试线程池
public class TestPool {
public static void main(String[] args) {
//创建服务,创建线程池
//newFixedThreadPool 参数为 线程池大小
ExecutorService executorService = Executors.newFixedThreadPool(10);
//执行
executorService.execute(new MyThread());
executorService.execute(new MyThread());
executorService.execute(new MyThread());
executorService.execute(new MyThread());
//关闭链接
executorService.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}