多线程
简介
Process进程,至少包含一个线程,可以包含多个线程
Thread线程
线程创建
三种创建方式:
Thread class 继承Thread类 重点
Runnable接口 实现Runnable接口(重点)最重要,上面的Thread就是实现了该接口
Callable接口 实现Callable(了解
Thread类
1)自定义线程继承Thread类
2)重写run方法,编写线程执行体
3)创建线程对象,调用start()方法启动线程
注意:调用run方法是只有主线程一条执行路径,
调用start方法是多条执行路径,主线程和子线程交替执行,图例:
线程不一定立即执行,看cpu调度
package ThreadStudy.demo01;
//创建线程方式一:继承Thread类,重写run方法,调用start()方法启动
public class TestThread01 extends Thread{
public static void main(String[] args) {
//main 主线程
//创建一个线程对象
TestThread01 testThread01 = new TestThread01();
//调用start方法开启线程
// 注意:调用run方法是只有主线程一条执行路径,
//
// 调用start方法是多条执行路径,主线程和子线程交替执行,图例:
testThread01.start();
for (int i = 0;i<20;i++){
System.out.println("学习多线程"+i);
}
}
@Override
public void run() {
//run方法线程体
for (int i = 0;i<20;i++){
System.out.println("看代码"+i);
}
}
}
多线程简单练习多线程,实现多线程同步下载图片
package ThreadStudy.demo01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//练习多线程,实现多线程同步下载图片
public class TestThread02 extends Thread{
private String url;
private String name;
public TestThread02(){
}
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://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy91SkRBVUtyR0M3TEJFaWF4Z2liZGdpYzd3WVdOSXZ3aGo4eFI1VFZiQ1lpY3Vvb3ZsNDA0OTJHeWlhYzVqaWE1elViRjkyalAwSVBKUFVXTHRsMEtyVXRpYnp0UEEvNjQw?x-oss-process=image/format,png","1.png");
TestThread02 testThread02 = new TestThread02("https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy91SkRBVUtyR0M3TEJFaWF4Z2liZGdpYzd3WVdOSXZ3aGo4eFI1VFZiQ1lpY3Vvb3ZsNDA0OTJHeWlhYzVqaWE1elViRjkyalAwSVBKUFVXTHRsMEtyVXRpYnp0UEEvNjQw?x-oss-process=image/format,png","2.png");
TestThread02 testThread03 = new TestThread02("https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy91SkRBVUtyR0M3TEJFaWF4Z2liZGdpYzd3WVdOSXZ3aGo4eFI1VFZiQ1lpY3Vvb3ZsNDA0OTJHeWlhYzVqaWE1elViRjkyalAwSVBKUFVXTHRsMEtyVXRpYnp0UEEvNjQw?x-oss-process=image/format,png","3.png");
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接口
1)自定义线程实现Runnable接口
2)重写run方法,编写线程执行体
3)创建线程对象,调用start()方法启动线程
推荐使用实现接口,因为java的单继承的局限
package ThreadStudy.demo01;
//创建线程方式二:实现Runnable接口,重写run方法,调用start()方法启动
public class TestThread03 implements Runnable{
public static void main(String[] args) {
//main 主线程
//创建一个线程对象
TestThread03 testThread03 = new TestThread03();
//调用start方法开启线程
// 注意:调用run方法是只有主线程一条执行路径,
//
// 调用start方法是多条执行路径,主线程和子线程交替执行,图例:
// Thread thread = new Thread(testThread03);
// thread.start();
//上面可以简写为:
new Thread(testThread03).start();
for (int i = 0;i<20;i++){
System.out.println("学习多线程"+i);
}
}
@Override
public void run() {
//run方法线程体
for (int i = 0;i<20;i++){
System.out.println("看代码"+i);
}
}
}
并发问题:
//多个线程同时操作一个对象//买火车票的例子//存在问题不同人拿到了同一张票
package ThreadStudy.demo01;
//多个线程同时操作一个对象
//买火车票的例子
//存在问题不同人拿到了同一张票
public class TestThread04 implements Runnable {
private int ticketNums = 10;
@Override
public void run() {
while (true){
if(ticketNums<=0){
break;
}
//模拟延时
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums+"张票");
ticketNums--;
}
}
public static void main(String[] args) {
TestThread04 t4 = new TestThread04();
new Thread(t4,"小明").start();
new Thread(t4,"老师").start();
new Thread(t4,"黄牛").start();
}
}
模拟龟兔赛跑
package ThreadStudy.demo01;
//模拟龟兔赛跑
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==0){
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
boolean flag = gameOver(i);
//比赛结束停止程序
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
}
}
//判断是否完成比赛
public boolean gameOver(int steps){
//判断是否有胜利者
if (winner!=null){
return true;
}
{
if (steps==100){
winner=Thread.currentThread().getName();
System.out.println("winner是:"+winner);
}
}
return false;
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}
Callable接口
步骤:
1)实现Callable接口,需要返回值类型
2)重写call方法,需要抛出异常
3)创建目标对象
4)创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
5)提交执行:Future<Boolean> result1 = ser.submi(t1);
6)获取结果:boolean r1 = result1.get()
7)关闭服务 ser.shutdownNow();
好处:可以定义返回值,可以抛出异常
package ThreadStudy.demo02;
import ThreadStudy.demo01.TestThread02;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//线程创建方式三:实现Callable接口
public class TestCallable implements Callable<Boolean> {
private String url;
private String name;
public TestCallable(){
}
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 testThread01 = new TestCallable("https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy91SkRBVUtyR0M3TEJFaWF4Z2liZGdpYzd3WVdOSXZ3aGo4eFI1VFZiQ1lpY3Vvb3ZsNDA0OTJHeWlhYzVqaWE1elViRjkyalAwSVBKUFVXTHRsMEtyVXRpYnp0UEEvNjQw?x-oss-process=image/format,png","1.png");
TestCallable testThread02 = new TestCallable("https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy91SkRBVUtyR0M3TEJFaWF4Z2liZGdpYzd3WVdOSXZ3aGo4eFI1VFZiQ1lpY3Vvb3ZsNDA0OTJHeWlhYzVqaWE1elViRjkyalAwSVBKUFVXTHRsMEtyVXRpYnp0UEEvNjQw?x-oss-process=image/format,png","2.png");
TestCallable testThread03 = new TestCallable("https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy91SkRBVUtyR0M3TEJFaWF4Z2liZGdpYzd3WVdOSXZ3aGo4eFI1VFZiQ1lpY3Vvb3ZsNDA0OTJHeWlhYzVqaWE1elViRjkyalAwSVBKUFVXTHRsMEtyVXRpYnp0UEEvNjQw?x-oss-process=image/format,png","3.png");
//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> r1 = ser.submit(testThread01);
Future<Boolean> r2 = ser.submit(testThread02);
Future<Boolean> r3 = ser.submit(testThread03);
//获取结果
boolean rs1 = r1.get();
boolean rs2 = r2.get();
boolean rs3 = r3.get();
System.out.println("1:"+rs1+"2"+rs2+"3"+rs3);
//关闭服务
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方法出现异常");
}
}
}
静态代理模式
好处:
代理对象可以做真实对象做不了的事
真实对象可以专注自己的事
package ThreadStudy.demo02;
//静态代理模式总结:
//真实对象和代理对象都需要实现同一个接口
//代理对象要代理真实角色
public class StaticProxy {
public static void main(String[] args) {
You you = new You();
new Thread( ()-> System.out.println("我爱你")).start();//这个也是通过静态代理,start类似下面的HappyMarry方法
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 before() {
System.out.println("结婚前,准备婚礼");
}
private void after() {
System.out.println("结婚后,收取佣金");
}
}
Lambda表达式
避免匿名内部类定义过多,让代码更加简洁
函数式接口
任何接口,如果只包含唯一一个的抽象方法,就是一个函数式接口
对于函数式接口,我们可以通过Lambda表达式来创建该接口的对象
package ThreadStudy.lambda;
/*
* 推导lambda表达式
* */
public class TestDemo {
//3. 静态内部类
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();
//6:用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");
}
}
package ThreadStudy.lambda;
public class TestDemo02 {
public static void main(String[] args) {
// ILove love = (int a) -> {
// System.out.println("I Love you :"+a);
// };
//简化1 参数类型,多个参数也可以省略
// ILove love = (a) -> {
// System.out.println("I Love you :"+a);
// };
//简化2 括号
// /*ILove love = a -> {
// System.out.println("I Love you :"+a);
// };*/
//简化3 去掉花括号 因为代码只有一行才能简化,如果多行必须花括号
ILove love = a ->
System.out.println("I Love you :"+a);
love.love(2);
}
}
interface ILove{
void love(int a);
}
因为Runnable接口里面只有一个方法,Thread类实现了Runnable接口,所以可以使用lambda表达式
停止线程
不推荐使用jdk提供的stop(),destroy()方法,已经废弃
推荐让线程自己停下来
建议使用一个标志位进行终止变量,但flag=false时则线程停止运行
package ThreadStudy.state;
public class TestStop implements Runnable{
private boolean flag = true;
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==999){
//切换标志位,停止线程
testStop.stop();
System.out.println("线程该停止了");
}
}
}
public void stop(){
this.flag=false;
}
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("run......Thread"+i++);
}
}
}
线程休眠
sleep()方法:
存在异常InterruptedException
sleep时间到达后线程进入就绪态
sleep可以模拟网络延时,倒计时
每个对象都有一个锁,sleep不会释放锁
模拟网络延时,放大问题的发生性
package ThreadStudy.state;
import ThreadStudy.demo01.TestThread04;
//模拟网络延时,放大问题的发生性
public class TestSleep implements Runnable{
private int ticketNums = 10;
@Override
public void run() {
while (true){
if(ticketNums<=0){
break;
}
//模拟延时
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums+"张票");
ticketNums--;
}
}
public static void main(String[] args) {
TestThread04 t4 = new TestThread04();
new Thread(t4,"小明").start();
new Thread(t4,"老师").start();
new Thread(t4,"黄牛").start();
}
}
倒计时
package ThreadStudy.state;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSleep2 {
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();
}
}
}
public static void tenDown() throws InterruptedException{
int num = 10;
while (true){
Thread.sleep(1000);
System.out.println(num--);
if (num<=0){
break;
}
}
}
}
线程礼让
礼让线程,让当前正在执行的线程暂停,但不进入阻塞状态
将线程从运行变为就绪态
让cpu重新调度,礼让不一定成功,看cpu
package ThreadStudy.state;
//测试礼让线程,礼让不一定成功看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合并线程
Join合并线程,待此线程执行完后,再执行其他线程,其他线程阻塞
即插队
线程状态
Thread t = new Thread() new新生态
调用start方法 就绪态
调用sleep方法,wait或者同步锁定时线程进入 阻塞态
运行状态 线程才是真正执行线程体的代码块
dead死亡状态,线程中断或者结束,一但进入死亡状态无法再次启动
package ThreadStudy.state;
//测试线程状态
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);
}
}
}
线程优先级
优先级范围从1---10
优先级高不一定先执行,优先级高以为着被cpu调用概率高
先设置优先级,在启动线程
package ThreadStudy.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(2);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);
t4.start();
//优先级只有1---》10
t5.setPriority(12);
t5.start();
t6.setPriority(-1);
t6.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"--->优先级:"+Thread.currentThread().getPriority());
}
}
守护线程daemon
线程分为用户线程和守护线程
虚拟机必须确保用户线程( main线程......)执行完毕,不用等待守护线程( 垃圾回收线程......)执行完毕
package ThreadStudy.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);//默认为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 < 365; i++) {
System.out.println("一生");
}
System.out.println("结束");
}
}
线程同步
多个线程操作同一个资源
并发
同一个对象被多个线程操作
解决方法,进入对象的等待池形成队列
队列和锁
保证安全需要锁
锁机制synchronized
当一个线程获得对象的排他锁,独占资源,其他线程必须等待,使用后释放锁
存在问题:
一个线程持有锁会导致其他所有需要此锁的线程挂起
在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题
如果一个优先级高的线程等待一个优先级低的线程释放锁会导致 优先级倒置引起性能问题
不安全案例
package ThreadStudy.syn;
//不安全的买票
//线程不安全
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"WO").start();
new Thread(buyTicket,"YOU").start();
new Thread(buyTicket,"花牛").start();
}
}
class BuyTicket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true;//外部停止方式
@Override
public void run() {
while (true){
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--);
}
}
线程不安全的集合
package ThreadStudy.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(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
同步方法
synchronized关键字,两种使用方法 synchronized方法 和 synchronized块
如果把一个大的方法设置为synchronized会影响效率
synchronized方法 锁的是类本身,synchronized块可以锁任何
锁的对象就是锁变化的量,需要增删改的对象
synchronized方法案例:
package ThreadStudy.syn;
//不安全的买票 修改为synchronized同步方法
//线程不安全
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"WO").start();
new Thread(buyTicket,"YOU").start();
new Thread(buyTicket,"花牛").start();
}
}
class BuyTicket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true;//外部停止方式
@Override
public void run() {
while (true){
buy();
}
}
//synchronized同步方法,锁的是this
private 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--);
}
}
synchronized块案例:
package ThreadStudy.syn;
//不安全的线程方法
//两个人去银行取钱
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100,"结婚基金");
Drawing you = new Drawing(account,50,"你");
Drawing she = new Drawing(account,100,"它");
you.start();
she.start();
}
}
//账户
class Account{
int money;//余额
String name;//卡名
public Account() {
}
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行模拟取钱
class Drawing extends Thread{
Account account;
int drawing;
String name;
int nowMoney;
public Drawing(Account account, int drawing, String name) {
this.account = account;
this.drawing = drawing;
this.name = name;
}
//synchronized 默认锁的是this,因为这里数据操作的是账户,所以这里无法使用synchronized方法,没有效果
//锁的对象就是锁变化的量,需要增删改的对象
@Override
public void run() {
//同步块
synchronized (account){
//判断有没有钱
if (account.money-drawing<0){
System.out.println(Thread.currentThread().getName()+"账户余额不够,取不了");
return;
}
//sleep 放大发生问题的安全性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money = account.money - drawing;
nowMoney = nowMoney + drawing;
System.out.println(Thread.currentThread().getName()+"余额为:"+account.money);
System.out.println(this.getName()+"手里的钱为:"+nowMoney);
}
}
}
package ThreadStudy.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(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
测试JUC安全类型的集合
package ThreadStudy.syn;
import java.util.concurrent.CopyOnWriteArrayList;
//测测试JUC安全类型的集合
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
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());
}
}
死锁
某一个同步块同时拥有两个以上的对象的锁时,就有可能发生死锁问题
产生死锁四大条件
互斥条件,请求与保持等待,不剥夺条件,循环等待
死锁例子:
package ThreadStudy.Lock;
//死锁:多个线程相互抱着对方需要的资源,然后形成僵持
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+"两秒钟后获得口红的锁");
}
}
}
}
}
解决把嵌套的synchronized块拿出来,不嵌套
Lock(锁)
ReentrantLock 可重复锁 实现Lock接口
可以显示的定义锁
package ThreadStudy.Lock;
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;
//定义locksuo
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();
}
}
}
}
Lock与synchronized对比
Lock是显式锁(手动开启和关闭锁)synchronized是隐式锁,出了作用域自动释放
Lock只有代码块锁,synchronized有代码块锁和方法锁
使用Lock锁,JVM会花费较少的时间来调度线程,性能更好,并且具有更好的扩展性(提供的更多的子类)
使用顺序:
Lock > 同步代码块 (已经进入了方法体,分配了相应资源) > 同步方法(在方法体之外
线程协作
操作系统的pv操作
生产者和消费者问题
缓冲区方法代码:
package ThreadStudy.Lock;
//测试:生产者和消费者问题——————>利用缓存区解决:管程法
//生产者 消费者 产品 缓冲区
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++) {
System.out.println("生产了"+i+"件");
container.push(new Chicken(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;
}
}
信号灯法
wait方法等待
notifyAll方法唤醒
java中的wait/notify的等待唤醒机制可以实现线程间的通信,wait使当前线程进入等待,该操作会使线程阻塞,直到其它线程唤醒(调用notify、notifyAll方法)它才可继续执行。
-
wait()、notify()/notifyAll()都是定义在 Object类的final方法,不支持重写。
-
wait()、notify()/notifyAll()都和对象监视器密切相关,所以这几个方法都需和synchronized搭配使用。
-
wait()方法在已获取锁的前提下,使当前线程阻塞,释放当前锁,等待其它线程唤醒。
-
notify()唤醒此对象监视器上阻塞等待的单个线程,不释放锁,被唤醒的线程参与到锁的竞争中。
-
notifyAll()唤醒此对象监视器上阻塞等待的所有线程,不释放锁,被唤醒的所有线程参与到锁的竞争中。
-
wait() 应配合 while 循环使用,不应使用 if ,务必在 wait() 调用前后都检查条件,如果不满足,必须调用
notify() 唤醒另外的线程来处理,自己继续 wait() 直至条件满足再往下执行。
notify() 是对 notifyAll() 的一个优化,但它有很精确的应用场景,并且要求正确使用。不然可能导致死
锁。正确的场景应该是 WaitSet 中等待的是相同的条件,唤醒任一个都能正确处理接下来的事项,如果
唤醒的线程无法正确处理,务必确保继续 notify() 下一个线程,并且自身需要重新回到 WaitSet 中 .
package ThreadStudy.Lock;
//测试生产者消费者问题:信号灯法,标志位解决
public class TestPCTwo {
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;//表演的节目
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;
}
}
线程池
提前创建多个线程放入线程池中,使用时直接获取,使用完放回去,可以避免频繁的创建和销毁,实现重复利用,类似生活中的公共交通工具
好处
-
提高响应速度(减少了创建新线程的时间
-
减低资源消耗(重复利用线程池中的线程,不需要每次都创建
-
便于线程管理(
corePoolSize:核心池大小
maximumPoolSize:最大线程数
KeepAliveTime:线程没有任务最多保持多长时间后会终止
ExecutorService:真正的线程池接口
-
void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
例子:
package ThreadStudy.Lock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//测试线程池
public class TestPool {
public static void main(String[] args) {
//创建线程池
ExecutorService service = Executors.newFixedThreadPool(10);//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());
}
}
-
<T>Future<T> submit(Callable<T> task):执行任务,有返回值,一般用来执行Callable
例子
package ThreadStudy.demo02;
import ThreadStudy.demo01.TestThread02;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//线程创建方式三:实现Callable接口
public class TestCallable implements Callable<Boolean> {
private String url;
private String name;
public TestCallable(){
}
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 testThread01 = new TestCallable("https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy91SkRBVUtyR0M3TEJFaWF4Z2liZGdpYzd3WVdOSXZ3aGo4eFI1VFZiQ1lpY3Vvb3ZsNDA0OTJHeWlhYzVqaWE1elViRjkyalAwSVBKUFVXTHRsMEtyVXRpYnp0UEEvNjQw?x-oss-process=image/format,png","1.png");
TestCallable testThread02 = new TestCallable("https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy91SkRBVUtyR0M3TEJFaWF4Z2liZGdpYzd3WVdOSXZ3aGo4eFI1VFZiQ1lpY3Vvb3ZsNDA0OTJHeWlhYzVqaWE1elViRjkyalAwSVBKUFVXTHRsMEtyVXRpYnp0UEEvNjQw?x-oss-process=image/format,png","2.png");
TestCallable testThread03 = new TestCallable("https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy91SkRBVUtyR0M3TEJFaWF4Z2liZGdpYzd3WVdOSXZ3aGo4eFI1VFZiQ1lpY3Vvb3ZsNDA0OTJHeWlhYzVqaWE1elViRjkyalAwSVBKUFVXTHRsMEtyVXRpYnp0UEEvNjQw?x-oss-process=image/format,png","3.png");
//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> r1 = ser.submit(testThread01);
Future<Boolean> r2 = ser.submit(testThread02);
Future<Boolean> r3 = ser.submit(testThread03);
//获取结果
boolean rs1 = r1.get();
boolean rs2 = r2.get();
boolean rs3 = r3.get();
System.out.println("1:"+rs1+"2"+rs2+"3"+rs3);
//关闭服务
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方法出现异常");
}
}
}
-
void shutdown() 关闭连接池
Executors:线程池的工具类,用于创建返回不同类型的线程池
总结
创建线程
package ThreadStudy.ReView;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
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;
}
}