day12--多线程
多线程
一、线程简介
任务、进程、线程、多线程
程序、进程、线程
一个进程可以有多个线程
process与thread
进程是执行程序的一次执行过程,它是一个动态的概念,是系统资源分配的单位
通常一个进程中可以包含若干个线程,一个进程至少有一个线程,不然没有存在的意义,线程是CPU调度和执行的单位。
核心概念
- 线程就是独立的执行路径
- 在程序运行时,即使没有自己创建线程,后台也会有多个线程,如果主线程,GC线程。
- main()称之为主线程,为系统的入口 ,用于执行整个程序。
- 在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调度,调度器是与操作系统紧密相关的,先后顺序是不能人为的干预的
- 对同一份资源的操作时,会存在资源抢夺的问题,需要加入并发控制
- 线程会带来额外的开销,如cpu调度时间,并发控制开销
- 每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
二、线程实现
1、线程创建
三种创建方式 Thread 、Runnable、Callable
继承Thread类
实现Runnable接口
实现Callable接口
2、Thread
自定义Thread类
重写run()方法
调用start()方法开启线程
public class TestThread01 extends Thread{
//main() 是主线程
public static void main(String[] args) {
//创建子线程
TestThread01 testThread01 = new TestThread01();
testThread01.start();
for (int i = 0; i < 20; i++) {
System.out.println("我在学习----------"+ i);
}
}
@Override
public void run() {
//执行代码
for (int i = 0; i < 20; i++) {
System.out.println("我在写代码++++++"+ i);
}
}
}
总结
线程开启不一定立即执行,由cpu调度执行
实现多线程同步下载图片
引入类库 commons-io-2.11.jar
FileUtils.copyURLToFile()
public class TestThread02 extends Thread{
private String url;
private String name;
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 tt1 = new TestThread02("https://kuangstudy.oss-cn-beijing.aliyuncs.com/bbs/2021/08/16/kuangstudy0ff38edc-4f3e-477a-9655-314a8f28d55b.jpg","1.jpg");
TestThread02 tt2 = new TestThread02("https://kuangstudy.oss-cn-beijing.aliyuncs.com/bbs/2021/07/29/kuangstudy81a070b2-d92c-48c4-aebd-5933137bf3a7.jpg","2.jpg");
TestThread02 tt3 = new TestThread02("https://kuangstudy.oss-cn-beijing.aliyuncs.com/bbs/2021/07/29/kuangstudy4d1c9284-e9c7-456b-b63b-b4aa76b04c06.jpg","3.jpg");
tt1.start();
tt2.start();
tt3.start();
}
}
class WebDownloader{
public void downLoader(String url, String filename){
try {
FileUtils.copyURLToFile(new URL(url),new File(filename));
} catch (IOException e) {
System.out.println("下载网络图片异常!"+ e.toString());
}
}
}
3、Runnable
定义MyRunnable类实现Runnable接口
实现run()方法
调用start(),需要丢入实现了Runnable接口的类
public class TestThread03 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("写代码 -----------"+ i);
}
}
public static void main(String[] args) {
TestThread03 testThread03 = new TestThread03();
new Thread(testThread03).start();
for (int i = 0; i < 20; i++) {
System.out.println("学习多线程++++++++"+ i);
}
}
}
小结
- 继承Thread类
- 实现Runnable接口
4、多线程并发
Thread.currentThread()
Thread.sleep()
多个线程操作同一个资源的情况下,线程不安全,数据混乱。
5、龟兔赛跑
public class Race implements Runnable{
private String winner;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (Thread.currentThread().getName().equals("兔子") && (i%10 == 1)){
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (gameOver(i)){
break;
}
System.out.println(Thread.currentThread().getName()+ "跑了"+i +"步");
}
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
public boolean gameOver(int step){
if (winner != null){
return true;
}else{
if (step == 100){
winner = Thread.currentThread().getName();
System.out.println(Thread.currentThread().getName()+ "赢了!");
return true;
}
}
return false;
}
}
6、Callable接口
- 实现Callable接口,需要返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象
- 创建执行服务 ExecutorService ser= Executors.newFixedThreadPool(1)
- 提交执行 Future
result1 = ser.submit(t1) - 获取结果 boolean r1 = result1.get()
- 关闭服务 ser.shutdownNow()
public class TestThread05 implements Callable<Boolean> {
private String url;
private String name;
public TestThread05(String url,String name){
this.url = url;
this.name = name;
}
@Override
public Boolean call() {
WebDownloader03 webDownloader = new WebDownloader03();
webDownloader.downLoader(url,name);
System.out.println("文件下载完成:"+ name);
return true;
}
public static void main(String[] args) {
TestThread05 tt1 = new TestThread05("https://kuangstudy.oss-cn-beijing.aliyuncs.com/bbs/2021/08/16/kuangstudy0ff38edc-4f3e-477a-9655-314a8f28d55b.jpg","1.jpg");
TestThread05 tt2 = new TestThread05("https://kuangstudy.oss-cn-beijing.aliyuncs.com/bbs/2021/07/29/kuangstudy81a070b2-d92c-48c4-aebd-5933137bf3a7.jpg","2.jpg");
TestThread05 tt3 = new TestThread05("https://kuangstudy.oss-cn-beijing.aliyuncs.com/bbs/2021/07/29/kuangstudy4d1c9284-e9c7-456b-b63b-b4aa76b04c06.jpg","3.jpg");
//创建执行服务
ExecutorService service = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> submit1 = service.submit(tt1);
Future<Boolean> submit2 = service.submit(tt2);
Future<Boolean> submit3 = service.submit(tt3);
//获取结果
try {
Boolean res1 = submit1.get();
Boolean res2 = submit2.get();
Boolean res3 = submit3.get();
System.out.println(res1);
System.out.println(res2);
System.out.println(res3);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
//关闭服务
service.shutdownNow();
}
}
class WebDownloader03{
public void downLoader(String url, String filename){
try {
FileUtils.copyURLToFile(new URL(url),new File(filename));
} catch (IOException e) {
System.out.println("下载网络图片异常!"+ e.toString());
}
}
}
总结
- 可以定义返回值
- 可以抛出异常
三、线程状态
1、 静态代理
我帮你去做一些事情
真实对象和代理对象都要实现同一个接口
代理对象要代理真实角色
代理对象可以做很多真实对象做不了的事情
真实对象专注做自己的事情
2、Lamda表达式
-
希腊字母表中排序第十一位的字母,英语名称为Lamda
-
避免匿名内部类定义过多
-
其实质属于函数式编程的概念
new Thread(()->System.out.println("多线程学习")).start();
为什么要用?
- 避免匿名内部类定义过多
- 可以让你的代码看起来很简洁
- 去悼了一堆没有意义的代码,只留下核心的逻辑
函数式接口是学习lambda表达式的关键 所在
函数式接口定义:
任何接口,如果只包含唯一 一个抽象方法,那么它就是一个函数式接口。
public interface Runnable{
public abstract void run();
}
对于函数式接口,我们可以通过lambda表达式来创建该接口的对象。
public class TestLamda {
//2、静态内部类
public static class Like2 implements ILike{
@Override
public void like() {
System.out.println("lamda 表达式 02");
}
}
public static void main(String[] args) {
ILike like = new Like();
like.like();
like = new Like2();
like.like();
//3、局部内部类
class Like3 implements ILike{
@Override
public void like() {
System.out.println("lamda 表达式 03");
}
}
like = new Like3();
like.like();
//4、匿名内部类
like = new ILike() {
@Override
public void like() {
System.out.println("lamda 表达式 04");
}
};
like.like();
//5、lamda表达式
like = ()-> {
System.out.println("lamda 表达式 05");
};
like.like();
//6、简化lamda表达式
like = ()->System.out.println("lamda 表达式 06");
like.like();
}
}
interface ILike{
void like();
}
//1.外部类方式
class Like implements ILike{
@Override
public void like() {
System.out.println("lamda 表达式 01");
}
}
带参Lamda表达式
public class TestLamda02 {
public static void main(String[] args) {
ILove love = a -> System.out.println("I love you "+ a);
love.love(520);
ILove2 love2 = (a,b)->{
System.out.println("I love you "+ a);
System.out.println("I love you too "+b);
};
love2.love(520,502);
}
}
interface ILove{
void love(int a);
}
interface ILove2{
void love(int a,int b);
}
3、线程的5大状态
- 创建状态
- 就绪状态
- 运行状态
- 阻塞状态
- 死亡状态
4、线程方法
- setPriority
- sleep
- join
- yield
- interrupt
- isAlive
建议使用标志位来停止线程
public class TestThread06 implements Runnable{
private boolean flag = true;
public static void main(String[] args) {
TestThread06 testThread06 = new TestThread06();
new Thread(testThread06).start();
for (int i = 0; i < 500; i++) {
if (i == 400){
testThread06.stop();
System.out.println("别跑了");
}
System.out.println("main");
}
}
@Override
public void run() {
while (flag){
System.out.println("我一直在跑");
}
}
public void stop(){
this.flag = false;
}
}
每一个对象都有一个锁,sleep不会释放锁
模拟网络延时,放大问题的发生性
public class TestThread07 implements Runnable{
public static int num = 10;
@Override
public void run() {
while (num > 0) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "拿了第" + num-- + "张票");
}
}
public static void main(String[] args) {
TestThread07 testThread07 = new TestThread07();
new Thread(testThread07,"我").start();
new Thread(testThread07,"别人").start();
new Thread(testThread07,"黄牛").start();
}
}
SimpleDateFormat()
public static void main(String[] args) throws InterruptedException {
TestThread08 testThread08 = new TestThread08();
new Thread(testThread08).start();
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());
}
}
线程礼让
让当前正在执行的线程暂停,但不阻塞
将线程从运行状态转为就绪状态
让cpu重新调度,礼让不一定成功
线程强制执行,Thread.join
public class TestThread10 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("线程执行第"+i + "次");
}
}
public static void main(String[] args) {
TestThread10 testThread10 = new TestThread10();
Thread thread = new Thread(testThread10);
thread.start();
for (int i = 0; i < 100; i++) {
System.out.println("main执行 "+ i);
if (i == 10){
try {
System.out.println("线程插队");
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
线程状态观测
Thread.State
线程中断或者结束就不能再次启动
public class TestThread11 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("线程执行");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
TestThread11 testThread11 = new TestThread11();
Thread thread = new Thread(testThread11);
Thread.State state = thread.getState();
System.out.println(state);
thread.start();
state = thread.getState();
System.out.println(state);
while (thread.getState() != Thread.State.TERMINATED){
try {
Thread.sleep(200);
state = thread.getState();
System.out.println(state);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
先设置优先级再启动 (1-10)默认5
public class TestThread12 implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+ "执行了");
}
public static void main(String[] args) {
TestThread12 testThread12 = new TestThread12();
Thread a = new Thread(testThread12, "a");
a.setPriority(1);
Thread b = new Thread(testThread12, "b");
b.setPriority(10);
Thread c = new Thread(testThread12, "c");
c.setPriority(7);
Thread d = new Thread(testThread12, "d");
d.setPriority(8);
a.start();
b.start();
c.start();
d.start();
}
守护线程daemon
线程分为用户线程和守护线程
虚拟机必有确保用户线程执行完毕
虚拟机不用等待守护线程执行完毕
setDaemon(true)
public class TestDaemon {
public static void main(String[] args) {
You you = new You();
God god = new God();
new Thread(you).start();
Thread thread = new Thread(god);
thread.setDaemon(true);
thread.start();
}
}
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("开心每一天");
}
System.out.println("=====godbye world=======");
}
}
class God implements Runnable{
@Override
public void run() {
while (true){
System.out.println("上帝在守护着你");
}
}
}
四、线程同步
多个线程操作同一个资源
线程同步其实就是一种等待机制,多个需要同时访问此对象的线程,需要对象等待池,形成队列,等待前一个线程使用完毕,下一个再使用。
队列和锁
锁机制 synchronized
- 一个线程持有锁会导致其他所有需要此锁的线程挂起
- 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题
- 如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题
线程不安全
- 买票不安全
- 不安全的取钱
- 线程不安全(ArrayList)
synchronized 方法和synchronized 块
方法里面需要修改的内容才需要锁
锁太多浪费资源
public class TestUnsafe01 {
public static void main(String[] args) {
Taciet taciet = new Taciet();
new Thread(taciet,"我").start();
new Thread(taciet,"你").start();
new Thread(taciet,"黄牛").start();
}
}
class Taciet implements Runnable{
private int num =10;
@Override
public synchronized void run() {
while (num>0){
System.out.println(Thread.currentThread().getName()+"买了"+num-- + "票");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
同步块:synchronized(obj){}
public class TestUnsafe02 {
public static void main(String[] args) {
Account a = new Account(100, "基金");
new Drawing(a,50,"我").start();
new Drawing(a,100,"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 drawMoney;
int nowMoney;
public Drawing(Account account,int drawMoney,String name){
super(name);
this.account = account;
this.drawMoney = drawMoney;
}
@Override
public void run() {
synchronized (account) {
if (account.money -drawMoney < 0) {
System.out.println("账户钱不够了");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money = account.money - drawMoney;
System.out.println(Thread.currentThread().getName() + "取了" + drawMoney);
System.out.println("银行余额" + account.money);
}
}
}
锁的对象就是变化的量
public class TestUnsafe03 {
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(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
CopyOnWriteArrayList 线程安全的
死锁
多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形,某一个同步块同时拥有两个以上对象的锁时,就可能会发生死锁的问题。
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 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;
}
public void makeUp() throws InterruptedException {
if (choice == 0){
synchronized (lipstick){
System.out.println(girlName +"拿到了口红");
Thread.sleep(1000);
synchronized (mirror){
System.out.println(girlName + "拿到了镜子");
}
}
}else{
synchronized (mirror){
System.out.println(girlName +"拿到了镜子");
Thread.sleep(2000);
synchronized (lipstick){
System.out.println(girlName + "拿到了口红");
}
}
}
}
@Override
public void run() {
try {
makeUp();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
产生死锁的四个必要条件
- 互斥条件:一个资源每次只能被一个进程使用
- 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
- 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺
- 循环等待条件:若干进程之间形成一种头尾相撞的循环等待资源关系
Lock
通过显式定义同步锁对象来实现同步。
ReentrantLock类实现了Lock
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{
private final ReentrantLock lock = new ReentrantLock();
private int num =10;
@Override
public void run() {
while (true){
try {
lock.lock();
if (num>0) {
System.out.println(num--);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
break;
}
}finally {
lock.unlock();
}
}
}
}
五、线程通信问题
线程协作
1、生产者消费者模式
线程通信
- wait()
- notify()
- wait(long timeout)
- notifyAll()
2、管程法
- 生产者负责生产数据
- 消费者负责处理数据
- 利用缓冲区解决
生产者、消费者、产品、缓冲区
public class TestThread13 {
public static void main(String[] args) {
SyncContainer syncContainer = new SyncContainer();
new Proudct(syncContainer).start();
new Consumer(syncContainer).start();
}
}
//生产者线程
class Proudct extends Thread{
SyncContainer syncContainer;
public Proudct(SyncContainer syncContainer){
this.syncContainer = syncContainer;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
syncContainer.push(new Chichen(i));
System.out.println("生产了第"+ i +"只鸡");
}
}
}
//消费者线程
class Consumer extends Thread{
SyncContainer syncContainer;
public Consumer(SyncContainer syncContainer){
this.syncContainer = syncContainer;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("消费了第"+syncContainer.pop().id+"只鸡");
}
}
}
//产品
class Chichen {
int id;
public Chichen(int id) {
this.id = id;
}
}
//缓冲区
class SyncContainer{
Chichen[] chichens = new Chichen[10];
private int counts;
//放入缓冲区
public synchronized void push(Chichen chichen){
//如果容器满了就等待
if (counts == 10){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
chichens[counts] = chichen;
counts++;
this.notifyAll();
}
//从缓冲区取走
public synchronized Chichen pop(){
//缓冲区为空
if (counts == 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
counts--;
Chichen chichen = chichens[counts];
this.notifyAll();
return chichen;
}
}
4、信号灯法
通过设置标志位解决
public class TestThread14 {
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 {
String voice;
boolean flag = true; //标志
public synchronized void play(String voice){
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.flag = !this.flag;
this.voice = voice;
System.out.println("表演:"+voice);
this.notifyAll();
}
public synchronized void watch(){
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.flag = !this.flag;
System.out.println("观看:"+voice);
this.notifyAll();
}
}
5、线程池
使用线程池
- 背景:经常创建和销毁使用且特别大的资源,比如并发情况下的线程,对性能影响很大
- 思路
- 好处
ExecutorService 和 Executors
ThreadPool
execute() 无返回值
submit() 有返回值
shutdown()
public class TestThread15 {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(new Eat());
service.execute(new Eat());
service.execute(new Eat());
service.execute(new Eat());
service.execute(new Eat());
service.shutdownNow();
}
}
class Eat implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
六、高级主题
总结
1、继承Thread类
2、实现Runnable接口
3、实现Callable接口
FutureTask

浙公网安备 33010602011771号