1. 多线程详解
基本概念
- 程序
- 进程
- 线程
1. Thread 类
- 自定义线程类继承Thread类
- 重写run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
package com.xiancheng.lesso01;
public class TestThread1 extends Thread{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 2; i++) {
System.out.println("我在看代码------"+i);
}
}
public static void main(String[] args) {
TestThread1 testThread1 = new TestThread1();//创建一个线程对象
testThread1.start();//调用start()方法开启线程
for (int i = 0; i < 100; i++) {
System.out.println("我在学习多线程-------------"+i);
}
}
}
1.2 网图下载
1.先下载包
package com.xiancheng.lesso01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//实现多线程同步下载图片
public class TestThread2 extends Thread{
private String url;//网络图片地址
private String name;//保存的文件名
public TestThread2(String url,String name){
this.url = url;
this.name = name;
}
public void run() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了文件名为"+name);
}
public static void main(String[] args) {
TestThread2 t1 = new TestThread2("https://g-search1.alicdn.com/img/bao/uploaded/i4/i3/2215452432714/O1CN01q7moka1Vv3jdSrhIG_!!0-item_pic.jpg_230x230.jpg_.webp","回力.jpg");
TestThread2 t2 = new TestThread2("https://g-search3.alicdn.com/img/bao/uploaded/i4/i4/2336221782/O1CN01S56iNa1P2CdTPLxnM_!!2336221782.jpg_180x180.jpg_.webp","安踏.jpg");
TestThread2 t3 = new TestThread2("https://g-search3.alicdn.com/img/bao/uploaded/i4/i3/1676193080/O1CN01asLoN81YcgfxRsimb_!!0-item_pic.jpg_180x180.jpg_.webp","椰子.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异常,dowmloader出现问题");
}
}
}
1.3 Runnable 接口
- 定义 MyRunnable 类实现Runnable接口
- 实现run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
package com.xiancheng.lesso01;
public class TestThread3 implements Runnable{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 200; i++) {
System.out.println("我在看代码-----------------"+i);
}
}
public static void main(String[] args) {
//创建runnable接口的实现类对象
TestThread3 testThread3 = new TestThread3();
new Thread(testThread3).start();
for (int i = 0; i < 1000; i++) {
System.out.println("我在学习多线程-----------"+i);
}
}
}
小结
- 继承Thread类
- 子类继承Thread类具有多线程能力
- 启动线程:子类对象.start()
- 不建议使用:避免OOP单继承局限性
- 实现Runnable接口
- 实现接口Runnable具有多线程能力
- 启动线程:传入目标对象+Thread对象.start()
- 推荐使用:避免单继承的局限性,灵活方便,方便同一个对象被多个线程使用
龟兔赛跑
package com.xiancheng.lesso01;
//模拟龟兔赛跑
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 == 80 ){
try {
Thread.sleep(50);
} 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;
}{
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();
}
}
1.4 Callable接口(了解即可)
package com.xiancheng.lesson02;
import com.xiancheng.lesso01.TestThread2;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//线程创建方式三:Callable接口
/*
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;
}
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://g-search1.alicdn.com/img/bao/uploaded/i4/i3/2215452432714/O1CN01q7moka1Vv3jdSrhIG_!!0-item_pic.jpg_230x230.jpg_.webp", "回力.jpg");
TestCallable t2 = new TestCallable("https://g-search3.alicdn.com/img/bao/uploaded/i4/i4/2336221782/O1CN01S56iNa1P2CdTPLxnM_!!2336221782.jpg_180x180.jpg_.webp", "安踏.jpg");
TestCallable t3 = new TestCallable("https://g-search3.alicdn.com/img/bao/uploaded/i4/i3/1676193080/O1CN01asLoN81YcgfxRsimb_!!0-item_pic.jpg_180x180.jpg_.webp", "椰子.jpg");
ExecutorService ser = Executors.newFixedThreadPool(1); //创建执行服务
Future<Boolean> result1 = ser.submit(t1);//提交执行
Future<Boolean> result2 = ser.submit(t2);
Future<Boolean> result3 = ser.submit(t3);
boolean r1 = result1.get();//获取结果
boolean r2 = result2.get();
boolean r3 = result3.get();
System.out.println(r1);//打印结果
System.out.println(r2);
System.out.println(r3);
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异常,dowmloader出现问题");
}
}
}
1.5 静态代理
package proxystatic;
public class StaticProxy {
public static void main(String[] args) {
new Thread( () -> System.out.println("woaini")).start(); //Lamda
yourself yourself = new yourself();
//yourself.HappyMarry();
WeddingCompany weddingCompany = new WeddingCompany(yourself);
weddingCompany.HappyMarry();
}
}
interface Marry{ //创建接口
void HappyMarry();
}
class yourself 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("结婚之前,布置");
}
}
1.6 Lambda表达式
- new Thread (() -> System.out.println(“多线程学习。。。。”)).start();
- 任何接口,如果只包含唯一一个抽象方法,那么他就是【函数式接口】
- 对于函数式接口可以使用lambda
演变过程(一):普遍方法
package lambdaShow;
public class TestLambda1 {
public static void main(String[] args) {
ILike like = new Like(); //利用接口来创建
like.lambda();
}
}
//1.定义一个函数式接口
interface ILike{
void lambda();
}
//2.实现类
class Like implements ILike{
@Override
public void lambda() {
System.out.println("I like ball");
}
}
演变过程(二):静态内部类
package lambdaShow;
public class TestLambda1 {
//3.静态内部类
static class Like2 implements ILike{
@Override
public void lambda() {
System.out.println("I like ball2");
}
}
public static void main(String[] args) {
ILike like = new Like2();
like.lambda();
}
}
//1.定义一个函数式接口
interface ILike{
void lambda();
}
演变过程(三):局部内部类
package lambdaShow;
public class TestLambda1 {
public static void main(String[] args) {
//4.局部内部类
class Like3 implements ILike{
@Override
public void lambda() {
System.out.println("I like ball3");
}
}
ILike like = new Like3();
like.lambda;
}
}
//1.定义一个函数式接口
interface ILike{
void lambda();
}
演变过程(四):匿名内部类
package lambdaShow;
public class TestLambda1 {
public static void main(String[] args) {
//5.匿名内部类,没有类的名称,必须借助接口或者父类
ILike like = new ILike() {
@Override
public void lambda() {
System.out.println("I like ball4");
}
};
like.lambda();
}
}
//1.定义一个函数式接口
interface ILike{
void lambda();
}
演变过程(尾):Lambda
package lambdaShow;
public class TestLambda2 {
public static void main(String[] args) {
ILove love = () -> {System.out.println("I like ball5");};
love.lambda();
}
}
//1.定义一个函数式接口
interface ILove{
void lambda();
}
带参数的Lambda
package lambdaShow;
public class TestLambda2 {
public static void main(String[] args) {
ILove love = (a) -> {
System.out.println("I like ball5"+a);
};
love.lambda(521);
}
}
//1.定义一个函数式接口
interface ILove{
void lambda(int a);
}
2. 线程工具
2.1 线程停止-stop
- 建议线程正常停止 -----> 利用次数,不建议死循环
- 建议使用标志位 -------> 设置一个标志位
- 不要使用stop等过时的方法
package com.xiancheng.state;
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){
testStop.stop();
System.out.println("线性该停止了");
}
}
}
}
2.2 线程休眠-sleep
- sleep指定当前线程阻塞的毫秒数
- sleep存在异常InterruptedException
- 每个对象都有一个锁,sleep不会释放锁
模拟倒计时
package com.xiancheng.state;
///模拟倒计时
public class TestSleep {
public static void main(String[] args) {
try {
tenDown();
} 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;
}
}
}
}
时钟
package com.xiancheng.state;
import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSleep {
public static void main(String[] args) {
//打印当前系统时间
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();
}
}
}
}
2.3 线程礼让-yield
- 礼让线程,让当前正在执行的线程暂停,但不阻塞
package com.xiancheng.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()+"线程结束执行");
}
}
2.4 线程强制执行-join
- 插队
- 下面的主线程和thread线程开始一起跑的-------到i=200之后,才只进行thread线程
package com.xiancheng.state;
public class Testjoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("线程vip"+i);
}
}
public static void main(String[] args) throws InterruptedException {
//启动我们的线程
Testjoin testjoin = new Testjoin();
Thread thread = new Thread(testjoin);//之所以写的复杂,是后面要调用thread
thread.start();
//主线程
for (int i = 0; i < 1000; i++) {
if (i==200){
thread.join();//插队
}
System.out.println("main"+i);
}
}
}
2.5 线程状态观测
- 线程对象一旦创建就进入到了新生状态
- 线程中断或者结束,一旦进入死亡状态,就不能再次启动
package com.xiancheng.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(1000);
state = thread.getState();//更新线程状态
System.out.println(state);//输出状态
}
}
}
结果
NEW
RUNNABLE
TIMED_WAITING
TIMED_WAITING
RUNNABLE
TIMED_WAITING
/
TERMINATED
2.6 线程的优先级
- 线程的优先级用数字表示,范围1~10
- 获取和改变优先级-----getPriority、setPriority(int xxx)
- 先设置优先级在启动
- 优先级低只是意味着获取调度的概率低,并不是优先级低就不会被调用,看CPU
package com.xiancheng.state;
//测试线程的优先级
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,"thread1");
Thread thread2 = new Thread(myPriority,"thread2");
Thread thread3 = new Thread(myPriority,"thread3");
Thread thread4 = new Thread(myPriority,"thread4");
Thread thread5 = new Thread(myPriority,"thread5");
Thread thread6 = new Thread(myPriority,"thread6");
//设置优先级,在启动
thread6.start();
thread1.setPriority(Thread.MAX_PRIORITY);
thread1.start();
thread5.setPriority(Thread.MIN_PRIORITY);
thread5.start();
thread4.setPriority(Thread.NORM_PRIORITY);
thread4.start();
thread2.setPriority(2);
thread2.start();
thread3.setPriority(8);
thread3.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
结果
main–>5
thread1–>10
thread3–>8
thread6–>5
thread4–>5
thread5–>1
thread2–>2
2.7 守护线程-daemon
- 线程分为用户线程和守护线程
- 虚拟机必须要确保用户线程执行完毕
- 虚拟机不用等待守护线程执行完毕
package com.xiancheng.state;
//测试守护线程
public class TestDaemo {
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 < 36000; i++) {
System.out.println("开心的活着");
}
System.out.println("=======拜拜");
}
}
3. 线程同步
-
并发:多个线程操作同一资源
-
形成条件:队列+锁
-
锁机制:synchronized
- 一个线程持有锁会导致其他所有需要此锁的线程挂起
- 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题
- 如果一个优先级高的线程等待一个优先级低的线程释放锁,会导致优先级倒置,引起性能问题
-
synchronized 方法
- 控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞
- 同步方法:public synchronized void method( int args ){}
- 方法里面需要修改的内容才需要锁,锁太多,浪费资源
-
synchronized块:同步块
- synchronized(Obj){}
- Obj称之为同步监视器
- Obj 可以使任何对象,但是推荐使用共享资源作为同步监视器
- 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者class
- 同步监视器的执行过程
- 第一个线程访问,锁定同步监视器,执行其中代码
- 第二个线程访问,发现同步监视器被锁定,无法访问
- 第一个线程访问完毕,解锁同步监视器
- 第二个线程访问,发现同步监视器没有锁,先锁定在执行代码
L1. 买票
package com.xiancheng.syn;
//不安全买票
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"a").start();
new Thread(station,"b").start();
new Thread(station,"c").start();
}
}
class BuyTicket implements Runnable{
private int ticktNums = 10;//票
boolean flag = true;//外部停止方式
@Override
public void run() {
//买票
while (flag) {
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//同步方法,锁的是this
private synchronized void buy() throws InterruptedException{
if (ticktNums<=0){//判断是否有票
flag = false;
return;
}
//模拟延时
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+"拿到了"+ticktNums--); //买票显示
}
}
L2. 银行取钱
package com.xiancheng.syn;
//不安全的取钱
//两个人去银行取钱
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(10000,"shang");
Drawing drawing1 = new Drawing(account,500,"你");
Drawing drawing2 = new Drawing(account,450,"我");
Drawing drawing3 = new Drawing(account,800,"他");
drawing1.start();
drawing2.start();
drawing3.start();
}
}
//账户
class Account{
int monry;
String name;
public Account(int monry, String name) {
this.monry = monry;
this.name = name;
}
}
//银行
class Drawing extends Thread{
Account account;//账户
int drawingMoney;//取了多少钱
int nowMoney = 0;//现在手里还有多少钱
boolean flag = true;//外部停止方式
public Drawing(Account account,int drawingMoney ,String name){
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
//取钱
@Override
public void run() {
while (flag){
synchronized (account){//-----------------------同步块
//判断有没有钱
if (account.monry-drawingMoney <= 0){
System.out.println(Thread.currentThread().getName()+"钱不够");
flag = false;
return;
}
//sleep可以放大问题
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.monry -= drawingMoney;//卡内余额
nowMoney += drawingMoney;//手里的钱
System.out.println(account.name+"账户还有余额为:"+account.monry);
//Thread.currentThread().getName() = this.getName()两个语句是一个意思
System.out.println(Thread.currentThread().getName()+"手里的钱为"+nowMoney);
}
}
}
}
结果:
shang账户还有余额为:9500
你手里的钱为500
shang账户还有余额为:9000
你手里的钱为1000
shang账户还有余额为:8200
他手里的钱为800
shang账户还有余额为:7750
我手里的钱为450
shang账户还有余额为:6950
他手里的钱为1600
shang账户还有余额为:6150
他手里的钱为2400
shang账户还有余额为:5650
你手里的钱为1500
shang账户还有余额为:4850
他手里的钱为3200
shang账户还有余额为:4400
我手里的钱为900
shang账户还有余额为:3600
他手里的钱为4000
shang账户还有余额为:3100
你手里的钱为2000
shang账户还有余额为:2300
他手里的钱为4800
shang账户还有余额为:1850
我手里的钱为1350
shang账户还有余额为:1050
他手里的钱为5600
shang账户还有余额为:250
他手里的钱为6400
你钱不够
他钱不够
我钱不够
===============================================================
L3. 集合
package com.xiancheng.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());
}
}
结果:
10000
JUC
package com.xiancheng.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());
}
}
4. 死锁Lock
- 死锁:多个线程互相抱着对方需要的额资源,然后形成僵持
- 产生死锁的四个必要条件
- 互斥条件:一个资源每次只能被一个进程使用
- 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
- 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺
- 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
package com.xiancheng.deadlock;
public class DeadLock {
public static void main(String[] args) {
Makeup girl1 = new Makeup(0,"灰姑娘");
Makeup girl2 = new Makeup(1,"白雪公主");
girl1.start();
girl2.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){//获得口红的锁======1
System.out.println(this.girlName+"获得口红的锁");
Thread.sleep(1000);
}
synchronized (mirror){//一秒钟后想获得镜子=====2
System.out.println(this.girlName+"获得镜子的锁");
}
}else {
synchronized (mirror){//获得镜子的锁======3
System.out.println(this.girlName+"获得镜子的锁");
Thread.sleep(2000);
}
synchronized (lipstick){//两秒钟后想获得口红======4
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
1. Lock锁
- ReentrantLock:可重入锁
- ReentrantLock类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显式加锁、释放锁
- 基本表达式
class A{
private final ReentrantLock lock = new ReentrantLock();
public void m(){
lock.lock();
try{
}finally{
lock.unlock();
}
}
}
- 示例
package com.xiancheng.gaoji;
import java.util.concurrent.locks.ReentrantLock;
//测试Lock锁
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2,"a").start();
new Thread(testLock2,"b").start();
new Thread(testLock2,"c").start();
}
}
class TestLock2 implements Runnable{
int ticketNums = 10;
private ReentrantLock lock = new ReentrantLock(); //定义Lock锁
@Override
public void run() {
while (true){
try {
lock.lock();//加锁
if (ticketNums >=0){
try {
Thread.sleep(1000);
} 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将花费较少的时间来调度线程
- 优先使用顺序:Lock-》同步代码块-》同步方法
5. 线程协作
生产者消费者模式
- Java提供了几个方法解决线程之间的通信问题
- wait():表示线程一直等待,直到其他线程 通知,与sleep(抱着锁睡觉)不同,会释放锁
- wait(long timeout):指定等待的毫秒数
- notify():唤醒一个处于等待状态的线程
- notify All():唤醒同一对象上所有调用wait()方法的线程,优先级别高的线程优先调度
- 注意:都是Object类的方法,都只在同步方法或者同步代码块中使用,否则会抛出异常IIIegalMonitorStataeException
1.管程法
package com.xiancheng.gaoji;
//测试:生产者消费者模型-->利用缓冲区解决:管程法
//生产者,消费者,产品,缓冲区
public class TestPC {
public static void main(String[] args) {
SynComtainer comtainer = new SynComtainer();
new Productor(comtainer).start();
new Consumer(comtainer).start();
new Consumer(comtainer).start();
new Consumer(comtainer).start();
}
}
//生产者
class Productor extends Thread {
SynComtainer comtainer;//创建一个容器
public Productor(SynComtainer comtainer) {
this.comtainer = comtainer;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
comtainer.push(new Chicken(i));
System.out.println("生产了第" + i + "只鸡");
}
}
}
//消费者
class Consumer extends Thread{
SynComtainer comtainer;//创建一个容器
public Consumer(SynComtainer comtainer){
this.comtainer = comtainer;
}
//消费
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+"消费了生产的第"+comtainer.pop()+"只鸡");
}
}
}
//产品
class Chicken{
int id;//编号
public Chicken(int id) {
this.id = id;
}
}
//缓冲区
class SynComtainer{
Chicken[] chickens = new Chicken[10];//需要一个容器大小
int count = 0;//容器计数器
//生产者放入产品
public synchronized void push(Chicken chicken){
//如果容器满了,就需要等待消费者消费
while (count == chickens.length){
//通知消费者消费,生产等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满,我们需要丢入产品
chickens[count] = chicken;
count++;
//可以通知消费者去消费
this.notifyAll();
}
//消费者消费产品
public synchronized int pop(){
//如果容器为空,就需要等待生产者生产
while (count == 0){
//通知生产者生产,消费等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果已经有产品,我们需要消费
count--;//必须先减减,将指针移到上一位置在取产品
Chicken chicken = chickens[count];
//吃完了,通知生产者生产
this.notifyAll();
return chicken.id;
}
}
2. 信号灯法
package com.xiancheng.gaoji;
public class TestPC2 {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
//演员
class Player extends Thread{
TV tv;
public Player(TV tv) {
this.tv = tv;
}
//表演
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (i%2==0){
tv.play("快乐大本营播放中");
}else {
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{
//演员表演,观众打分等待 T
//观众打分,演员表演等待 F
String voice;
boolean flag = true;
//表演
public synchronized void play(String voice){
if (flag = false){
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 = true){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"观看了:"+voice);
//通知演员表演
this.notifyAll();
this.flag = !this.flag;
}
}
线程池
- 思路:提取创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用
- 好处:
- 提高响应速度(减少了创建新线程的时间)
- 降低资源消耗
- 便于线程管理
- corePoolSize:核心池的大小
- maximumPoolSize:最大线程数
- keepAliveTime:线程没有任务时最多保持多长时间会终止
- 线程池相关的API:ExecutorService和Executor
- ExecutorService:真正的线程池接口。常见的子类Thread和PoolExecutor
- void execute(Runnable command):执行任务,没有返回值,一般用来执行Runnable
- void shutdown():关闭连接池
- Executors:工具类、线程池的工厂类,用来创建并返回不同类型的线程池
- ExecutorService:真正的线程池接口。常见的子类Thread和PoolExecutor
package com.xiancheng.gaoji;
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());
}
}