1. 核心概念
线程:独立的执行路径
main():主线程,系统的入口,执行整个程序
2.创建线程方式
方式一:继承Thread 实现run方法 调用start()开启线程 (不建议使用:避免OOP单继承局限性)
public class Thread01 extends Thread{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("我是一个线程----");
}
}
public static void main(String[] args) {
Thread01 thread01 = new Thread01();
thread01.start();
thread01.run();
for (int i = 0; i < 20; i++) {
System.out.println("我是main线程-----");
}
}
}
//线程不一定马上执行,CPU调度安排
package lib;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//实现多线程同步下载图片
public class Thread02 extends Thread{
private String url;
private String name;
public Thread02(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) {
Thread02 t1 = new Thread02("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.jj20.com%2Fup%2Fallimg%2F1114%2F0H320120Z3%2F200H3120Z3-6-1200.jpg&refer=http%3A%2F%2Fpic.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623726480&t=aeeb3812edf8560b9d9344f6f3a9f32f","1.jpg");
Thread02 t2 = new Thread02("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.jj20.com%2Fup%2Fallimg%2F1114%2F0H120155P2%2F200H1155P2-8-1200.jpg&refer=http%3A%2F%2Fpic.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623726480&t=a615c429d70d360a3ff91a4f54ed48bb","2.jpg");
Thread02 t3 = new Thread02("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fitbbs%2F1602%2F22%2Fc56%2F18513507_1456151497563_mthumb.jpg&refer=http%3A%2F%2Fimg.pconline.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623726729&t=b1422c32d3223d0c4dd1cc64faebcd15","3.jpg");
t1.start();
t2.start();
t3.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异常!");
}
}
}
方式二:实现Runnable接口 (推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用)
public class Thread03 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("我是一个线程----");
}
}
public static void main(String[] args) {
Thread03 thread03 = new Thread03();
// Thread thread = new Thread(thread03);
// thread.start();//代理模式
new Thread(thread03).start();
for (int i = 0; i < 20; i++) {
System.out.println("我是main线程-----");
}
}
}
方式三:实现callable接口
package chi.thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//实现多线程同步下载图片
//callable的好处:
//1.可以定义返回值
//2.可以抛出异常
public class TestCallable implements Callable<Boolean> {
private String url;
private String name;
public TestCallable(String url,String name){
this.url = url;
this.name = name;
}
@Override
public Boolean call() {
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("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.jj20.com%2Fup%2Fallimg%2F1114%2F0H320120Z3%2F200H3120Z3-6-1200.jpg&refer=http%3A%2F%2Fpic.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623726480&t=aeeb3812edf8560b9d9344f6f3a9f32f","1.jpg");
TestCallable t2 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.jj20.com%2Fup%2Fallimg%2F1114%2F0H120155P2%2F200H1155P2-8-1200.jpg&refer=http%3A%2F%2Fpic.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623726480&t=a615c429d70d360a3ff91a4f54ed48bb","2.jpg");
TestCallable t3 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fitbbs%2F1602%2F22%2Fc56%2F18513507_1456151497563_mthumb.jpg&refer=http%3A%2F%2Fimg.pconline.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623726729&t=b1422c32d3223d0c4dd1cc64faebcd15","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();
System.out.println(rs1);
System.out.println(rs2);
System.out.println(rs3);
ser.shutdown();
}
}
//下载器
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异常!");
}
}
}
3. 静态代理模式
//总结:真实对象和代理对象都要实现同一个接口
public class StaticProxy {
public static void main(String[] args) {
WeddingCompany weddingCompany = new WeddingCompany(new 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 before(){
System.out.println("结婚之前,布置现场");
}
private void after(){
System.out.println("收尾款");
}
}
4 并发问题
package chi.thread;
import java.sql.SQLOutput;
//初识并发问题
//发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
public class demo01 implements Runnable{
private int ticketNums = 10;//票数
@Override
public void run() {
while(true){
if(ticketNums<1){
break;
}
//模拟延时
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了"+ticketNums--+"票");
}
}
public static void main(String[] args) {
demo01 ticket = new demo01();
new Thread(ticket,"小明").start();
new Thread(ticket,"老师").start();
new Thread(ticket,"黄牛党").start();
}
}
5 实现龟兔赛跑
package chi.thread;
import sun.awt.windows.ThemeReader;
//模拟龟兔赛跑
public class Race implements Runnable{
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
//模拟兔子睡觉
if(Thread.currentThread().getName().equals("兔子")&&i==10){
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();
}
}
6 Lambda表达式
避免匿名内部类定义过多,其实质属于函数式编程的概念。
函数式接口
- 任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口。
public interface Runnable{
publid abstract void run();
}
- 对于函数式接口,我们可以通过Lambda表达式来创建该接口的对象。
package chi.thread;
public class TestLambda02 {
public static void main(String[] args) {
ILove love = null;
//1.lambda表示简化
love = (int a)-> {
System.out.println("i love you-->"+a);
};
//简化1.去掉参数类型
love = (a)->{
System.out.println("i love you-->"+a);
};
//简化2.简化括号
love = a->{
System.out.println("i love you-->"+a);
};
//简化3.去掉花括号,仅限于只有一行代码的情况
love = a-> System.out.println("i love you-->"+a);
//总结: 前提是接口为函数式接口
// 多个参数也可以去掉参数类型,如果去掉就全部去掉,必须加上括号
//
love.love(520);
}
}
interface ILove{
void love(int a);
}
7 线程状态
7.1 线程停止
package chi.thread;
import com.sun.org.apache.xpath.internal.operations.Bool;
//测试stop
//1.建议线程正常停止------->利用次数,不建议死循环。
//2.建议使用标志位--------->设置一个标志位
//3.不要使用stop或者destroy等过时或者JDK不建议使用的方法
public class TestStop implements Runnable{
// 1.设置一个标志位
private Boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("run.....Thread"+i++);
}
}
// 2.设置一个公开的方式停止线程,转换标志位
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){
// 调用stop方法切换标志位,让线程停止
testStop.stop();
System.out.println("线程该停止了");
}
}
}
}
7.2 线程休眠
package chi.thread;
import chi.OOP.demo05.D;
import java.text.SimpleDateFormat;
import java.util.Date;
//模拟倒计时
public class TestSleep2 implements Runnable{
public static void main(String[] args) {
// 模拟倒计时
try {
tenDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 打印系统当前时间
Date startTime = new Date(System.currentTimeMillis());//获取系统当前时间
while(true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis());//更新当前时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static public void tenDown() throws InterruptedException {
int num = 10;
while(true){
Thread.sleep(1000);
System.out.println(num--);
if (num<=0){
break;
}
}
}
@Override
public void run() {
}
}
7.3 线程礼让
礼让线程,让当前正在执行的线程暂停,但不阻塞,将线程从运行状态转为就绪状态,让CPU重新调度,礼让不一定成功!看CPU心情。
package chi.thread;
//测试礼让线程
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()+"线程停止执行");
}
}
7.4 Join
Join合并线程,待此线程执行完成后,再执行其他线程,可以想象成插队
package chi.thread;
//测试Join方法
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; 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 < 1000; i++) {
if (i==200){
try {
thread.join();//插队,main线程阻塞
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("main"+i);
}
}
}
7.5 线程状态观测
package chi.thread;
//观察测试线程的状态
public class TestState {
public static void main(String[] args) {
Thread thread = new Thread(()->{
for (int i = 0; i <5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
}
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){
// 只要线程不终止就一直输出它的状态
try {
Thread.sleep(100);
state = thread.getState();//更新线程状态
System.out.println(state);//输出状态
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
8 线程优先级
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器优先按照优先级决定应该调度哪个线程来执行。线程的优先级用数字表示,范围从1-10。可以使用以下方法改变或获取优先级:
getPriority()、setPriority(int xxx)
package chi.thread;
//测试线程优先级
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(5);
t5.start();
t6.setPriority(7);
t6.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
}
}
优先级只是被调用的概率,不一定高的就会被首先调用。
9 守护线程
线程分为用户线程和守护线程,虚拟机必须确保用户线程执行完毕,不用等待守护线程执行完毕,如后台记录操作日志,监控内存,垃圾回收等待。
package chi.thread;
//测试守护线程
//上帝守护你
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,表示是用户线程,正常的线程都是用户线程。
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 < 36500; i++) {
System.out.println("每天开心的活着!");
}
System.out.println("=======good bye ! World!=======");//Hello World!
}
}
10 线程同步
多个线程操作同一个资源
并发:同一个对象被多个线程同时操作
同步形成条件:队列+锁,每个对象都有一把锁,sleep不会释放锁
三个不安全案例
package synchronize;
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(12000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
package synchronize;
import chi.OOP.demo05.D;
//不安全的取钱
//两个人去银行取钱,账户
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,"女朋友");
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 (drawingMoney > account.money){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
//sleep 可以放大问题的发生性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额 - 取钱数目
account.money = account.money - drawingMoney;
//手里的钱 = 原来的钱 + 取钱数目
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name + "余额为:"+account.money);
// this.getName() = Thread.currentThread().getName()
System.out.println(this.getName()+"手里的钱:"+nowMoney);
}
}
package synchronize;
import chi.OOP.demo05.B;
//不安全的买票
//线程不安全,有负数
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;//票
Boolean flag = true;//外部停止方式
@Override
public void run() {
// 买票
while(flag){
buy();
}
}
public void buy(){
// 判断是否有票
if (ticketNums<=0){
flag = false;
return;
}
// 买票
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
10.1 同步方法
可以通过private关键字来保证数据对象只能被方法访问,所以只需要针对方法提出一套机制,就是synchronized关键字。方法里面需要修改的内容才需要锁,锁的太多浪费资源。它包括两种方式:
- public synchronized void method(int args){}
该方法控制对“对象”的访问,每个对象对应一把锁,方法一旦执行,就占了该锁,需要等到方法返回之后才会释放锁,后面的线程才可以获得这个锁,继续执行。缺陷为如果将一个大的方法申明为synchronized将会影响效率。
- 同步块:synchronized(obj){}
- obj称之为同步监视器,可以是任何对象,但是推荐使用共享资源作为同步监视器。
- 同步方法中无需指定同步监视器,因为同步方法中同步监视器就是this,就是这个对象本身,或者是class
package synchronize;
import chi.OOP.demo05.D;
//不安全的取钱
//两个人去银行取钱,账户
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,"女朋友");
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() {
// 判断钱多少
synchronized (account){
if (drawingMoney > account.money){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
//sleep 可以放大问题的发生性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额 - 取钱数目
account.money = account.money - drawingMoney;
//手里的钱 = 原来的钱 + 取钱数目
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name + "余额为:"+account.money);
// this.getName() = Thread.currentThread().getName()
System.out.println(this.getName()+"手里的钱:"+nowMoney);
}
}
}
package synchronize;
//不安全的买票
//线程不安全,有负数
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;//票
Boolean flag = true;//外部停止方式
@Override
public void run() {
// 买票
while(flag){
buy();
}
}
public synchronized void buy(){
// 判断是否有票
if (ticketNums<=0){
flag = false;
return;
}
// 买票
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
package synchronize;
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(12000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
11 死锁
死锁
package chi.thread;
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
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 (lipStick) {//获得镜子的锁
System.out.println(this.girlName + "获得镜子的锁");
Thread.sleep(1000);
synchronized (mirror) {//一秒钟后想获得口红
System.out.println(this.girlName + "获得口红的锁");
}
}
}
}
}
开锁
package chi.thread;
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
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 (lipStick) {//获得镜子的锁
System.out.println(this.girlName + "获得镜子的锁");
Thread.sleep(1000);
}
synchronized (mirror) {//一秒钟后想获得口红
System.out.println(this.girlName + "获得口红的锁");
}
}
}
}
死锁的四个必要条件:
- 互斥条件:一个资源每次只能被一个进程使用
- 请求于保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
- 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺
- 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
只要破除一个或多个就可以避免死锁的发生
12 Lock(锁)
package chi.thread;
import java.util.concurrent.locks.ReentrantLock;
//测试Lock锁
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;
private final ReentrantLock lock = new ReentrantLock();//定义Lock锁
@Override
public void run() {
try{
lock.lock();//加锁
while (true){
if(ticketNums < 1){
break;
}else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}
}
}finally {//解锁
lock.unlock();
}
}
}
13 线程协作(生产者消费者模式)
Java提供了几个方法解决线程之间的通信问题
- wait() 表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁。
- wait(long timeout)指定等待的毫秒数
- notify()唤醒一个处于等待状态的线程
- notifyAll()唤醒同一个对象上所有调用wait()方法的线程,优先级高的线程优先调度
解决方式一:管程法
生产者–>缓冲区–>消费者
package chi.thread;
//管程法-->缓冲区
public class TestPC {
public static void main(String[] args) {
SynContainer synContainer = new SynContainer();
Producer producer = new Producer(synContainer);
Consumer consumer = new Consumer(synContainer);
producer.start();
consumer.start();
}
}
//生产者
class Producer extends Thread{
SynContainer synContainer;
Producer(SynContainer synContainer){
this.synContainer = synContainer;
}
// 生产鸡
@Override
public void run() {
for (int i = 0; i < 100; i++) {
synContainer.push(new Chicken(i));
System.out.println(Thread.currentThread().getName()+"生产了"+i+"只鸡");
}
}
}
//消费者
class Consumer extends Thread{
SynContainer synContainer;
Consumer(SynContainer synContainer){
this.synContainer = synContainer;
}
//消费鸡
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+"消费了"+synContainer.pop().id+"只鸡");
}
}
}
//产品
class Chicken{
int id;//产品编号
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;
}
}
解决方式二:信号灯法
标志位
package chi.thread;
//标志位法,标志位解决
public class TestPC2 {
public static void main(String[] args) {
TV tv = new TV();
Watcher watcher = new Watcher(tv);
Player player = new Player(tv);
new Thread(player,"演员一号").start();
new Thread(watcher,"观众一号").start();
}
}
//生产者--->演员
class Player extends Thread{
TV tv;
Player(TV tv){
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if(i%2 == 0){
tv.play("快乐大本营");
}else {
tv.play("广告");
}
}
}
}
//消费者--->观众
class Watcher extends Thread{
TV tv;
Watcher(TV tv){
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.watch();
}
}
}
//产品--->TV
class TV{
// 表演者表演,观众等待 flag = true;观众观看,表演者等待 flag = false
String voice;//表演的节目
Boolean flag = true;//标志位
// 表演
public synchronized void play(String voice){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"表演了"+voice);
this.voice = voice;
this.flag = false;
// 通知观众进行观看
this.notifyAll();
}
// 观众观看
public synchronized void watch(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"观看了"+voice);
this.flag = true;
// 通知演员进行表演
this.notifyAll();
}
}
14 线程池
相关API:ExecutorService 和 Executors
ExecutorService:真正的线程池接口
void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
Future submit(Callable task):执行任务,有返回值,一般用来执行Callable
Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
void shutdown():关闭线程池
package chi.thread;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//测试线程池
public class TestPool {
public static void main(String[] args) {
// 1.创建线程池
// newFixedThreadPool 参数为:线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
// 执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
// 2.关闭连接
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}