多线程详解

多线程详解

1.进程和线程

  • 进程:说起进程就要说起程序。程序是指令和数据的有序集合,本身是一个静态概念。而进程则是执行程序的一次执行过程,是一个动态概念。是系统资源分配的单位。

  • 线程:独立执行的路径。通常在一个进程中可以包含多个线程,当然一个进程中至少有一个线程,不然没有存在的意义。线程是cpu调度和执行的单位。

真正的多线程是多核的(多个cpu),很多多线程是模拟出来的,只不过切换速度很快,我们感觉不出来而已。线程开启不一定立即执行,由cpu调度执行。

2.进程的实现

三种创建方式

1.继承Thread类(重点)(不推荐使用,避免OOP单继承局限性)

  • 继承Thread类(线程类)
  • 重写run方法(线程体)
  • 执行线程(start()方法)
package com.company;

public class TestThread01 extends Thread {
    @Override
    public void run() {
//        重写run线程
        for (int i = 0;i<20;i++){
            System.out.println("我在看代码"+i);
        }
    }

    //主线程
    public static void main(String[] args) {

        //创建一个对象调用线程
        TestThread01 testThread01 = new TestThread01();
        testThread01.start();
        //main线程
        for (int i =0;i<2000;i++){
            System.out.println("我在学习多线程"+i);
        }
    }
}

2.实现Runnable接口(重点)(避免单继承局限性,灵活方便,方便同一个对象被多个线程使用)

  • 实现runnable接口
  • 重写run方法
  • 执行线程需要丢入runnable接口实现类,调用start方法
package com.company;

public class TestThread03 implements Runnable{
    @Override
    public void run() {
//        重写run线程
        for (int i = 0;i<20;i++){
            System.out.println("我在看代码"+i);
        }
    }

    //主线程
    public static void main(String[] args) {
        //创建runnable接口的实现类对象
        TestThread03 testThread03 = new TestThread03();
        //创建线程对象,通过线程对象来开启我们的线程,代理
        Thread thread = new Thread(testThread03);
        thread.start();
        //main线程
        for (int i =0;i<2000;i++){
            System.out.println("我在学习多线程"+i);
        }
    }
}

实现Callable接口(了解)

并发:多个线程同时操作一个对象的时候会出现高并发的问题

3.静态代理模式

1.真实对象和代理对象都要实现同一个接口

2.代理对象要代理真实角色

好处:代理对象可以做好多真实对象做不了的事情,真实对象专注做自己的事情

4.Lambda表达式

目的:避免匿名内部类定义过多,其实质属于函数式编程的概念

函数式接口:任何接口,如果只包含一个抽象方法,那么它就是一个函数式接口。

对于函数式接口,我们可以用lambda表达式来创建该接口的对象。

//匿名内部类
public class TestLambda02 {
    public static void main(String[] args) {
        Ilove ilove = new Ilove() {
            @Override
            public void love(int a) {
                System.out.println("I love you-->"+a);
            }
        };
        ilove.love(2);
    }
}

interface Ilove{
    void love(int a);
}

package com.chen;

//匿名内部类
public class TestLambda02 {
    public static void main(String[] args) {
        Ilove ilove = (int a) -> {
            System.out.println("I love you-->" + a);
        };
        ilove.love(2);
    }
}

interface Ilove {
    void love(int a);
}

5.线程的5个状态

1.测试stop

package com.chen;
//测试stop
//1.建议线程正常停止--->利用次数,不建议死循环
//2.建议使用标志位--->设置一个标志位
//3.不要使用stop或者destroy等或者jdk不介意使用的方法
public class TestStop implements Runnable{
    //1.设置标识位
    private boolean flag = true;
    @Override
    public void run() {
        int i=0;
        while (flag){
            System.out.println("run...Thread"+i++);

        }
    }

    //设置一个公开的方法停止线程,转换标志位
    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("线程停止了");
            }
        }
    }
}

2.线程休眠:

每个对象都有一把锁,sleep不会释放这把锁

package com.chen;
//模拟倒计时
public class TestSheep {
    public static void main(String[] args) {
        try {
            tenDown();
        }
        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;
            }
        }
    }
}

3.线程礼让:

  • 礼让线程,让当前正在执行的线程暂停,但不阻塞
  • 让线程从运行状态转为就绪状态
  • 让CPU重新调度,礼让不一定成功

就是正在运行的A进程退出来和其他进程重新竞争,是否礼让成功看cpu

package com.chen;

//测试礼让线程
//礼让不一定成功,看cpu心情
public class TestYield {
    public static void main(String[] args) {
        MyYeild myYeild = new MyYeild();

        new Thread(myYeild,"A").start();
        new Thread(myYeild,"B").start();
    }

}
class MyYeild implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"线程开始执行");
        Thread.yield();//礼让
        System.out.println(Thread.currentThread().getName()+"线程结束");
    }
}

线程强制执行,即插队的过程,直到走完了,被插队的线程才能走

package com.chen;

//测试join方法,插队
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.start();

        //主线程
        for (int i =0;i<1000;i++){
            if (i==200){
                thread.join();//插队
            }
            System.out.println("main"+i);
        }
    }
}

观测线程状态Thread.State

package com.chen;

//观测线程的状态
public class TestState implements Runnable{
    @Override
    public void run() {

    }

    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("/");
            }

        });  //Lambda

        //观测状态
        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);
        }
    }
}

6.线程的优先级

  • getPriority
  • setPriority(int xxx)
package com.chen;

public class TestPriority {
    public static void main(String[] args) {
        //主线程的默认优先级
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
        Mypriority mypriority = new Mypriority();
        Thread t1 = new Thread(mypriority);
        Thread t2 = new Thread(mypriority);
        Thread t3 = new Thread(mypriority);
        Thread t4 = new Thread(mypriority);
        Thread t5 = new Thread(mypriority);
        Thread t6 = new Thread(mypriority);

        //先设置优先级,再启动
        t1.start();

        t2.setPriority(1);
        t2.start();

        t3.setPriority(4);
        t3.start();

        t4.setPriority(Thread.MAX_PRIORITY);
        t4.start();
        

    }
}


class Mypriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }
}

优先级低只是意味着获得调度的概率低,并不是优先级就不会被调用了,这都是看cpu的调度。

7.守护线程

线程分为用户线程和守护线程:

虚拟机必须确保用户线程执行完毕;

虚拟机不用等待守护线程执行完毕;(gc垃圾回收机制)

package com.test;

import org.omg.PortableServer.THREAD_POLICY_ID;

//测试守护线程
//上帝守护你
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");  //hello,world!

    }
}

8.线程同步(重难点)

并发:一个对象被多个线程同时操作

上万人同时抢票,两个银行都是取钱,所以一定要排队,所以我们需要线程同步,就是形成一种等待机制。

线程同步的形成条件:队列+锁,解决安全性问题

锁带来的问题:

1.会引起效率降低

2.当优先级高的线程等待优先级低的线程,会导致性能倒置问题

9.三大不安全实例

不安全的买票实例:会出现负数的情况:

package com.syn;

//不安全的买票
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();
        new Thread(station,"顺才").start();
        new Thread(station,"吴琦").start();
        new Thread(station,"聪聪").start();

    }
}

class BuyTicket implements Runnable {

    private int ticketnums = 10;
    private boolean flag = true;

    @Override
    public void run() {
        //买票
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    private void buy() throws InterruptedException {
        //判断是否有票
        if (ticketnums <= 0) {
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep(100);
        //买票
        System.out.println(Thread.currentThread().getName() + "拿到了" + ticketnums-- + "张票");
    }
}

银行取钱

package com.syn;

import sun.misc.PostVMInitHook;

import javax.management.remote.rmi._RMIConnection_Stub;

public class UnsafeBank {
    public static void main(String[] args) {
        BankAccount acco = new BankAccount(100, "基金");
        Bank you = new Bank(acco, 30, "你");
        Bank girlFriend = new Bank(acco, 30, "女朋友");

        you.start();
        girlFriend.start();
    }
}

//银行账户
class BankAccount {
    int money;//余额
    String name;//卡名

    public BankAccount(int money, String name) {
        this.money = money;
        this.name = name;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

//银行取款
class Bank extends Thread {
    private BankAccount account; //银行账户
    //取了多少钱
    int drawingMoney;
    //现在手里有多少钱
    int nowMoney;

    public BankAccount getAccount() {
        return account;
    }

    public void setAccount(BankAccount account) {
        this.account = account;
    }

    public int getDrawingMoney() {
        return drawingMoney;
    }

    public void setDrawingMoney(int drawingMoney) {
        this.drawingMoney = drawingMoney;
    }

    public int getNowMoney() {
        return nowMoney;
    }

    public void setNowMoney(int nowMoney) {
        this.nowMoney = nowMoney;
    }

    public Bank(BankAccount account, int drawingMoney, String name) {
        super();
        this.account = account;
        this.drawingMoney = drawingMoney;

    }

    //取钱
    @Override
    public void run() {
        //判断有没有钱
        if (account.getMoney() - drawingMoney < 0) {
            System.out.println(Thread.currentThread().getName() + "钱不够,取不了");
            return;
        }
        //银行卡里的钱减少
        account.money = account.money - drawingMoney;
        nowMoney = nowMoney + drawingMoney;
        System.out.println(account.getName() + "余额为:" + account.getMoney());
        System.out.println(this.getName() + "手里的钱:" + nowMoney);
    }
}


线程不安全的集合list,在多线程进行添加的时候会产生覆盖,输出的结果可能不为10000.

package com.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());
    }
}

10.同步方法及同步块

只需要在方法上加上synchronized关键词即可给该方法上锁

package com.syn;

//安全的买票
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();
        new Thread(station,"顺才").start();
        new Thread(station,"吴琦").start();
        new Thread(station,"聪聪").start();

    }
}

class BuyTicket implements Runnable {

    private int ticketnums = 10;
    private boolean flag = true;

    @Override
    public void run() {
        //买票
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    //同步方法,锁的是this
    private synchronized void buy() throws InterruptedException {
        //判断是否有票
        if (ticketnums <= 0) {
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep(100);
        //买票
        System.out.println(Thread.currentThread().getName() + "拿到了" + ticketnums-- + "张票");
    }
}

synchronized锁的是this,所以我们经常使用同步块,锁的对象应该是需要增删改的对象

11.死锁

死锁:多个线程互相抱着对方持有的资源,然后形成僵持

例如:

package com.thread;

//死锁:多个线程互相抱着对方持有的资源,然后形成僵持
public class DeadLock {
    public static void main(String[] args) {
        MakeUp g1 = new MakeUp(0,"灰姑娘");
        MakeUp g2 = new MakeUp(1,"白雪公主");

        g1.start();
        g2.start();
    }
}


//口红
class Lipstick{

}

//镜子
class Mirror{

}

//化妆
class MakeUp extends Thread{
    //需要的资源只有一份,用static保证
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choice;//选择
    String girlName; //使用化妆品的人

    MakeUp(int choice,String girlName){
        this.choice = choice;
        this.girlName = girlName;
    }

    @Override
    public void run() {
        //化妆
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    //化妆,互相持有对方的锁,就是需要拿到对方的资源
    private void makeup() throws InterruptedException {
        if (choice==0){
            synchronized (lipstick){
                System.out.println(this.girlName + "获得口红的锁");
                Thread.sleep(1000);
                //一秒钟之后获得镜子的锁
                synchronized (mirror){
                    System.out.println(this.girlName + "获得镜子的锁");
                }
            }
        }else {
            synchronized (mirror){
                System.out.println(this.girlName + "获得镜子的锁");
                Thread.sleep(2000);

                //一秒钟之后获得口红
                synchronized (lipstick){
                    System.out.println(this.girlName + "获得口红的锁");
                }
            };
        }
    }

}

死锁如何避免:四个必要条件

package com.thread;

//死锁:多个线程互相抱着对方持有的资源,然后形成僵持
public class DeadLock {
    public static void main(String[] args) {

        MakeUp g1 = new MakeUp(0,"灰姑娘");
        MakeUp g2 = new MakeUp(1,"白雪公主");

        g1.start();
        g2.start();
    }
}


//口红
class Lipstick{

}

//镜子
class Mirror{

}

//化妆
class MakeUp extends Thread{
    //需要的资源只有一份,用static保证
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choice;//选择
    String girlName; //使用化妆品的人

    MakeUp(int choice,String girlName){
        this.choice = choice;
        this.girlName = girlName;
    }

    @Override
    public void run() {
        //化妆
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    //化妆,互相持有对方的锁,就是需要拿到对方的资源
    private void makeup() throws InterruptedException {
        if (choice==0){
            synchronized (lipstick){
                System.out.println(this.girlName + "获得口红的锁");
                Thread.sleep(1000);
            }
            synchronized (mirror){
                System.out.println(this.girlName + "获得口红的锁");

        }}else {
            synchronized (mirror){
                System.out.println(this.girlName + "获得镜子的锁");
                Thread.sleep(2000);

            };
            synchronized (lipstick){
                System.out.println(this.girlName + "获得口红的锁");
            }
        }
    }

}

12.Lock锁

ReentranLock类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentranLock,可以显示加锁。

利用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;
    //定义Lock锁
    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(Thread.currentThread().getName() + "拿到了" + ticketNums--);
                } else {
                    break;
                }

            } finally {
                //解锁
                lock.unlock();
            }

        }
    }
}
  • 优先使用顺序

    Lock>同步代码块>同步方法

13.生产者消费者问题——线程协作

具体问题看操作系统,需要用到Java中的wait()和notify()方法。生产者生产,消费者消费,两个进程之间需要通信。

解决生产者-消费者问题有如下几种方式:

1.管程法:

package com.gaoji;

import java.awt.*;
import java.security.PublicKey;

//测试生产者,消费者模型 -->利用缓冲区解决:管程法
//生产者,消费者,产品,缓冲区
public class TestPc {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();
        new Productor(container).start();
        new Customer(container).start();
    }
}

//生产者
class Productor extends Thread {
    SynContainer container;

    public Productor(SynContainer container) {
        this.container = container;
    }

    //生产
    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            container.push(new Chicken(i));
            System.out.println("生产了" + i + "只鸡");
        }
    }
}

//消费者
class Customer extends Thread {
    SynContainer container;

    public Customer(SynContainer container) {
        this.container = container;
    }
    
    //消费
    @Override
    public void run() {
        for (int i = 1; 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;
    }

}

2.信号灯法:

package com.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 = new 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 = new 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) {
            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;
    }

}

14.线程池

package com.gaoji;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//测试线程池
public class TestPool {
    public static void main(String[] args) {
        //1.创建服务,创建线程池
        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() {
        for (int i = 0; i < 1; i++) {
            System.out.println(Thread.currentThread().getName()+i);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值