多线程
线程简介
Process与Thread
进程是动态的概念
一个进程可以包含若干个线程
gc线程
线程的进行由调度器安排调度
存在资源抢夺的问题,需要加入并发控制每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
线程实现(重点)
Runnable接口
- 继承Thread类
- 子类继承Thread类具备多线程能力
- 启动线程:子类对象.start()
- 不建议使用:避免OOP单继承的局限性
- 实现Runnable接口
- 实现接口Runnable具有多线程的能力
- 启动线程:传入目标对象+Thread对象.strat()
- ==推荐使用:避免单继承局限性,灵活方便,方便一个对象被多个线程使用
继承Thread()类
package com.kuang.demo01;
//创建线程方式一:继承Thread类,重写run()方法,调用start方法开启线程
//总结注意:线程开启不一定立即执行,由CPU调度
public class TestThread01 extends Thread{
@Override
public void run() {
//run方法体
for (int i = 0; i < 200; i++) {
System.out.println("我在看代码--"+i);
}
}
//两个线程交替进行
public static void main(String[] args) {
//main线程,主线程
//创建一个线程对象
TestThread01 thread01 = new TestThread01();
//调用start方法开启线程
thread01.start();
for (int i = 0; i < 200; i++) {
System.out.println("我在学习多线程--"+i);
}
}
}
使用runnable接口实现多线程
package com.kuang.demo01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
/**
* 练习Thread ,实现多线程同步下载图片
*/
public class TestThread2 implements Runnable{
private String url; //保存的网络图片地址
private String name; //保存的文件名
public TestThread2(String url, String name){
this.name = name;
this.url = url;
}
//下载线程的执行体
@Override
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://www.kuangstudy.com/assert/images/index_topleft_logo_black.png","1.png");
TestThread2 t2 = new TestThread2("https://www.kuangstudy.com/assert/images/xiaok.png","2.png");
TestThread2 t3 = new TestThread2("https://img1.bdstatic.com/static/common/img/icon_cf1b905.png","3.png");
new Thread(t1).start();
new Thread(t2).start();
new Thread(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异常,downloader方法出现问题");
}
}
}
线程不安全举例
package com.kuang.demo01;
/**
* 多个线程操作一个对象
* 买火车票的例子
* 发现问题:多个线程操作一个资源的情况下,线程不安全,数据紊乱
*/
public class TestThread04 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) {
TestThread04 testThread04 = new TestThread04();
new Thread(testThread04,"小明").start();
new Thread(testThread04,"小红").start();
new Thread(testThread04,"老师").start();
}
}
模拟龟兔赛跑
package com.kuang.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(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
boolean flag = gameOver(i);
if(flag){
break;//如果比赛结束了就停止程序
}
System.out.println(Thread.currentThread().getName()+"-->跑了多少"+i+"步");
}
}
//判断是否完成比赛
public boolean gameOver(int step){
//判断是否有胜利者
if(winner!=null){
return true;
}else{
if(step>=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();
}
}
实现callable接口
package com.kuang.demo02;
import com.kuang.demo01.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 的好处
* 可以定义返回值
* 可以抛出异常
*/
public class TestCallable implements Callable<Boolean> {
private String url; //保存的网络图片地址
private String name; //保存的文件名
public TestCallable(String url, String name){
this.name = name;
this.url = url;
}
//下载线程的执行体
@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://www.kuangstudy.com/assert/images/index_topleft_logo_black.png","1.png");
TestCallable t2 = new TestCallable("https://www.kuangstudy.com/assert/images/xiaok.png","2.png");
TestCallable t3 = new TestCallable("https://img1.bdstatic.com/static/common/img/icon_cf1b905.png","3.png");
//创建执行服务:
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 = r1.get();
Boolean rs3 = r1.get();
System.out.println(rs1);
System.out.println(rs2);
System.out.println(rs3);
}
}
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 com.kuang.demo03;
/**
* 静态代理模式总结:
* 真实对象和代理对象都实现同一个接口
* 代理对象要代理真实角色
*
* 好处:
* 代理对象可以做很多真实对象做不了的事
* 真实对象专注做自己的事情
*/
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;
WeddingCompany(Marry target) {
this.target = target;
}
@Override
public void HappyMarry() {
before();
this.target.HappyMarry();//这就是真实对象
after();
}
private void after() {
System.out.println("结婚之后很痛苦");
}
private void before() {
System.out.println("结婚之前,布置现场");
}
}
Lamda表达式
-
为什么要使用
- 避免匿名内部类定义过多
- 让你的代码看起来很简洁
- 去掉了一堆没有意义的代码,只留下核心的逻辑
-
函数式接口的定义
- 任何接口,如果只包含唯一一个抽象方法,那么他就是一个函数式接口
- 对于函数式接口,我们可以通过lambda表达式来创建该接口的对象
package com.kuang.lambda;
/**
* 推导lambda表达式
*/
public class TestLambda01 {
//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是一个接口,实例化为对象
like.lambda();
//4.局部内部类
class Like3 implements ILike{
@Override
public void lambda() {
System.out.println("i like lambda3");
}
}
like = new Like3();
like.lambda();
//5.匿名内部类,没有类的名称,必须借用接口或者父类
like = new ILike() {
@Override
public void lambda() {
System.out.println("i like lambda4");
}
};//这是一个语句,必须加分号
like.lambda();
//6.用lambda简化 因为函数型接口只有单个方法
like = ()-> {
System.out.println("i like lambda5");
};
like.lambda();
}
}
//1.定义一个函数式接口
interface ILike{
void lambda();
}
//2.实现类
class Like implements ILike{
@Override
public void lambda() {
System.out.println("i like lambda");
}
}
Lambda表达式化简
package com.kuang.lambda;
/**
* 总结:
* lambda表达式只有在一行代码的情况下才能化简为,如果有多行,则用代码块包裹
* 前提是接口为函数式接口
* 多个参数也可以去掉参数类型,要去掉就都去掉,必须加上括号
*/
public class TestLambda02 {
public static void main(String[] args) {
/* ILove love = (a)->{
System.out.println("i love -->" + a);
};*/
ILove love = a-> System.out.println("i love -->"+a);
love.love(520);
}
}
interface ILove{
void love(int a);
}
线程状态
- 创建状态
- 就绪状态
- 阻塞状态
- 运行状态
- 死亡状态
停止线程
- 推荐线程自己停下来
- 建议使用一个标志位进行终止变量
- 当flag= false 则线程终止
package com.kuang.state;
/**
* 测试stop
* 1.建议线程正常停止-->利用次数,不建议死循环
* 2.建议使用标志位-->设置一个标志位
* 3.不使用stop和destroy等过时方法
*/
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("线程该停止了");
}
}
}
}
线程休眠
- sleep(时间)指定当前程阻塞的毫秒数
- sleep存在异常InterruptedException
- sleep时间达到后线程进入就绪状态
- sleep可以模拟网络延时,倒计时等
- 每一个对象都有一个所,sleep不会释放锁
模拟网络延时
package com.kuang.state;
import com.kuang.demo01.TestThread04;
/**
* 模拟网络延时
* 问题的发生性
*/
public class TestSleep implements Runnable{
private int ticketNum = 10;
@Override
public void run() {
while (true){
if(ticketNum<=0){
break;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->买了第"+ticketNum--+"张票");
}
}
public static void main(String[] args) {
TestSleep testThread04 = new TestSleep();
new Thread(testThread04,"小明").start();
new Thread(testThread04,"小红").start();
new Thread(testThread04,"老师").start();
}
}
线程休眠的应用
package com.kuang.state;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 模拟倒计时
*/
public class TestSleep02 {
public static void main(String[] args) throws InterruptedException {
//打印当前系统时间
Date startTime = new Date(System.currentTimeMillis());//获取当前系统时间
while(true){
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis());//更新当前时间
}
}
public static void turnDown() throws InterruptedException {
int num = 10;
while(true){
Thread.sleep(1000);
System.out.println(num--);
if(num<=0){
break;
}
}
}
}
线程礼让
- 礼让线程,让当前正在执行的线程暂停,但不阻塞
- 将线程从运行状态转为就绪状态
- 让CUP重新调度,礼让不一定成功!看CPU心情
package com.kuang.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合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
-
可以想象成插队
package com.kuang.state;
/**
* 测试Join
* 可以理解为插队
*/
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("vip来了...快让开");
}
}
public static void main(String[] args) throws InterruptedException {
//启动我们的线程
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
//主线程
for (int i = 0; i < 500; i++) {
if(i==200){
thread.join();//子线程插队
}
System.out.println("main"+i);
}
}
}
线程状态
NEW
A thread that has not yet started is in this state.RUNNABLE
A thread executing in the Java virtual machine is in this state.BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.TERMINATED
A thread that has exited is in this state.
package com.kuang.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,还没有调用start方法
//观察启动
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);
}
//thread.start();
//线程中断或者结束,一旦进入死亡状态,就不能再次启动
}
}
线程优先级
- Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行
- 线程的优先级用数字表示,范围从1~10
- Thread.MIN_PRIORITY = 1;
- Thread.MAX_PRIORITY = 10;
- 使用以下方法改变或获取优先级
- getPriority()
- setPriority(int xxx)
package com.kuang.state;
/**
* 测试线程的优先级
*/
public class TestPriority {
public static void main(String[] args) {
//获取主线程的优先级
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread thread = new Thread(myPriority);
Thread thread1 = new Thread(myPriority);
Thread thread2 = new Thread(myPriority);
Thread thread3 = new Thread(myPriority);
Thread thread4 = new Thread(myPriority);
Thread thread5 = new Thread(myPriority);
Thread thread6 = new Thread(myPriority);
//设置优先级再启动
thread.start();
thread1.setPriority(1);
thread1.start();
thread2.setPriority(4);
thread2.start();
thread3.setPriority(Thread.MAX_PRIORITY);//设置为最高优先级
thread3.start();
thread4.setPriority(Thread.MIN_PRIORITY);
thread4.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
守护(daemon)线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不同等待守护线程执行完毕
- 如:后外记录操作日志,监控内存,垃圾回收等待
package com.kuang.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 < 36500; i++) {
System.out.println("你一直都很开心");
}
System.out.println("Goodbye World!");
}
}
线程同步(重点)
- 由于同一进程的多个进程共享用一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问的正确性,在访问时加入锁机制synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可,存在以下问题
- 降低性能
- 引起性能倒置
线程不安全的三个例子
package com.kuang.syn;
/**
* 例子:不安全的取钱
* 两个人去取钱
*/
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,"girlFriend");
you.start();
girlFriend.start();
}
}
//账户
class Account{
int balance;//余额
String name;//账户名
public Account(int balance, String name) {
this.balance = balance;
this.name = name;
}
}
//银行:模拟取款
class Drawing extends Thread{
Account account;//账户
//取了多少钱
int drawingMoney;
//现在手里有多少钱
int nowMoney;
public Drawing(Account account, int drawingMoney,String name){
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
//取钱
@Override
public void run() {
//判断有没有钱
if(account.balance-drawingMoney<=0){
System.out.println(Thread.currentThread().getName()+"-->账户余额不足");
return;
}
try {//sleep可以放大问题的发生性
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡里余额
account.balance-=drawingMoney;
nowMoney+=drawingMoney;
System.out.println(account.name+"的余额为:"+account.balance);
//Thread.currentThread().getName() = this.getName();
System.out.println(this.getName()+"手里的钱: "+nowMoney);
}
}
package com.kuang.syn;
/**
* 不安全的买票
* 线程不安全,有负数
*/
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"自己").start();
new Thread(buyTicket,"你们").start();
new Thread(buyTicket,"黄牛党").start();
}
}
class BuyTicket implements Runnable{
//票
private int TicketNUms = 10;
Boolean flag= true;
@Override
public void run() {
while (flag){
try {
Buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void Buy() throws InterruptedException {
//判断是否有票
if(TicketNUms<=1){
flag = false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"买到了,第"+TicketNUms--+"张票");
}
}
package com.kuang.syn;
import java.util.ArrayList;
import java.util.List;
/**
* 线程不安全的集合
*/
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
Thread.sleep(3000);
System.out.println(list.size());
}
}
同步方法
- synchronized方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行
- 缺陷:**若将一个大的方法申明为synchronized将会影响效率
- 方法里需要修改的内容才需要锁
- 锁的太多浪费资源
同步块
- synchronized(Obj){}
- Obj称为同步监视器
- Object可以是任何对象,但是推荐使用共享资源作为同步监视器
- 同步方法中无需指定同步监视器,因为同步方法中的同步监视器就是this,就是这个对象本身,或者是class
锁的对象就是变化的量,需要增删改查的对象
synchronized(account){//这里的共享资源是account
//判断有没有钱
if(account.balance-drawingMoney<=0){
System.out.println(Thread.currentThread().getName()+"-->账户余额不足");
return;
}
try {//sleep可以放大问题的发生性
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡里余额
account.balance-=drawingMoney;
nowMoney+=drawingMoney;
System.out.println(account.name+"的余额为:"+account.balance);
//Thread.currentThread().getName() = this.getName();
System.out.println(this.getName()+"手里的钱: "+nowMoney);
}
}
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized(list){
list.add(Thread.currentThread().getName());
}
}).start();
}
//synchronized 同步方法,锁的是this
private synchronized void Buy() throws InterruptedException {
//判断是否有票
if(TicketNUms<=0){
flag = false;
return;
}
//模拟延时
//买票
System.out.println(Thread.currentThread().getName()+"买到了,第"+TicketNUms--+"张票");
}
JUC安全类型集合
package com.kuang.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 com.kuang.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;//使用化妆品的人
public Makeup(int choice,String girlName){
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
//调用化妆方法
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup() throws InterruptedException {
if(choice==0){
synchronized (lipstick){//获得口红的锁
System.out.println(this.girlName+"获得口红的锁");
Thread.sleep(1000);
}
//不嵌套使用的话,使用完就释放
synchronized (mirror){//一秒钟后想获得镜子的锁
System.out.println(this.girlName+"获得镜子的锁");
}
}else{
synchronized (mirror){//获得镜子的锁
System.out.println(this.girlName+"获得镜子的锁");
Thread.sleep(2000);
}
synchronized (lipstick){//一秒钟后想获得口红的锁
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
线程通信问题
Lock(锁)
-
从JDK5.0开始,Java提供了更强大的线程同步机制——通过显示定义同步锁对象来实现同步。同步锁使用Lock对象充当
-
java.util.concurrent.Locks接口是控制多个线程对共享资源进行访问的工具
锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象
- RerentrantLock类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显式加锁、释放锁
package com.kuang.gaoji; 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 ticketNum = 10; //定义Lock锁 private final ReentrantLock lock = new ReentrantLock(); @Override public void run() { while (true){ try{ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } lock.lock();//加锁 if(ticketNum>0){ System.out.println(Thread.currentThread().getName()+"买到了-->"+ticketNum--); }else{ break; } }finally { lock.unlock();//解锁 } } } }
-
Lock是显示锁(手动开启和关闭锁),synchronized是隐式锁,出了作用域自动释放
-
Lock只有代码块锁,synchronized有代码块锁和方法锁
-
使用Lock锁,性能更好,扩展性更好
-
优先使用顺序
- Lock>同步代码块(已经 进入了方法体,分配了相应资源)>同步方法(在方法体之外)
高级主题
线程协作
- 生产者消费者模式
- 生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据
package com.kuang.gaoji;
/**
* 生产者消费者模型-->利用缓冲区解决:管程法
*/
//需要生产者,消费者,产品,缓冲区
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
//生产者
class Productor extends Thread{
SynContainer container;
public Productor(SynContainer container){
this.container = container;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Chicken(i));
System.out.println("生产了"+i+"只鸡");
}
}
}
//消费者
class Consumer extends Thread{
SynContainer container;
public Consumer(SynContainer container){
this.container = container;
}
//消费
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了-->"+container.pop().ID+"只鸡");
}
}
}
//产品
class Chicken{
int ID;//产品编号
public Chicken(int ID) {
this.ID = ID;
}
}
//缓冲区
class SynContainer{
//需要一个容器大小
Chicken[] chickens = new Chicken[10];
//容器计数器
int count = 0;
//生产者放入产品
public synchronized void push(Chicken chicken){
//如果容器满了,就需要等待消费者消费
if(count==chickens.length){
//通知消费者消费,生产者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满,我们就需要丢入产品
chickens[count] = chicken;
count++;
//可以通知消费者消费了
this.notifyAll();
}
//消费者消费产品
public synchronized Chicken pop(){
//判断能否消费
if(count==0){
//等待生产者生产,消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//吃完了,通知生产者生产
this.notifyAll();
return chicken;
}
}
信号灯法:
package com.kuang.gaoji;
/**
* 测试生产者消费者问题2:信号灯法,标志位解决
*/
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++) {
this.tv.watch();
}
}
}
//产品-->节目
class TV{
//演员表演的时候观众等待 T
//观众观看的时候,演员等待 F
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:线程没有任务时最多保持多长时间后会终止
- 线程池相关的API:ExecutorService和Executors
package com.kuang.gaoji;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* 回顾总结线程的创建
*/
public class ThreadNew {
public static void main(String[] args) {
new MyThread1().start();
//需要一个代理类
new Thread(new MyThread2()).start();
FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3());
new Thread(futureTask).start();
try {
Integer integer = futureTask.get();
System.out.println(integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
//1.继承Thread类
class MyThread1 extends Thread{
@Override
public void run() {
System.out.println("MyThread1");
}
}
//2.实现runnable接口
class MyThread2 implements Runnable{
@Override
public void run() {
System.out.println("MyThread2");
}
}
//3.实现callable接口
class MyThread3 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("MyThread3");
return 100;
}
}