多线程详解

本文详细介绍了Java中创建线程的两种主要方式:继承Thread类和实现Runnable接口,并通过实例展示了这两种方式的使用。同时,文章涵盖了线程生命周期、Thread类相关方法、线程同步、死锁、生产者消费者问题以及线程优先级和守护线程的概念,为理解Java多线程编程提供了全面的知识框架。
摘要由CSDN通过智能技术生成

创建线程的两种方式

常用的方法

在这里插入图片描述

/**
 * 测试Thread中的常用方法:
 * 1. start():启动当前线程;调用当前线程的run()
 * 2. run(): 通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法中
 * 3. currentThread():静态方法,返回执行当前代码的线程
 * 4. getName():获取当前线程的名字
 * 5. setName():设置当前线程的名字
 * 6. yield():释放当前cpu的执行权
 * 7. join():在线程a中调用线程b的join(),此时线程a就进入阻塞状态,直到线程b完全执行完以后,线程a才
 *           结束阻塞状态。
 * 8. stop():已过时。当执行此方法时,强制结束当前线程。
 * 9. sleep(long millitime):让当前线程“睡眠”指定的millitime毫秒。在指定的millitime毫秒时间内,当前
 *                          线程是阻塞状态。
 * 10. isAlive():判断当前线程是否存活
 *
 *
 * 线程的优先级:
 * 1.
 * MAX_PRIORITY:10
 * MIN _PRIORITY:1
 * NORM_PRIORITY:5  -->默认优先级
 * 2.如何获取和设置当前线程的优先级:
 *   getPriority():获取线程的优先级
 *   setPriority(int p):设置线程的优先级
 *
 *   说明:高优先级的线程要抢占低优先级线程cpu的执行权。但是只是从概率上讲,高优先级的线程高概率的情况下
 *   被执行。并不意味着只有当高优先级的线程执行完以后,低优先级的线程才执行。
 *
 *
 */

方式一:继承Thread类

在这里插入图片描述

package cn.tedu.thread;

public class ThreadDemo {
    //main方法的内容会放到底层主线程来执行
    public static void main(String[] args) {
        //创建线程对象---创建描述线程任务信息类的对象
        TDemo t=new TDemo();
        //调用父类的方法来开启线程
        //线程对象不能回头执行
        t.start();

        //主线程执行的内容
        for(int i=20;i>=0;i--){
            System.out.println("main:"+i);

            //线程休眠
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}


//定义类---描述线程的任务信息
class TDemo extends Thread{
    //重写的run方法就是线程的任务信息
    @Override
    public void run() {
        for(int i=0;i<20;i++){
            System.out.println("run:"+i);

            //线程休眠
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

在这里插入图片描述

创建Thread类的匿名子类方式

在这里插入图片描述

package atguigu.exer;

/**
 * 练习:创建两个分线程,其中一个线程遍历100以内的偶数,另一个线程遍历100以内的奇数
 */
public class ThreadDemo {
    public static void main(String[] args) {
//        MyThread1 m1 = new MyThread1();
//        MyThread2 m2 = new MyThread2();
//
//        m1.start();
//        m2.start();

        //创建Thread类的匿名子类的方式
        new Thread(){
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    if(i % 2 == 0){
                        System.out.println(Thread.currentThread().getName() + ":" + i);

                    }
                }
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    if(i % 2 != 0){
                        System.out.println(Thread.currentThread().getName() + ":" + i);

                    }
                }
            }
        }.start();

    }
}

class MyThread1 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ":" + i);

            }
        }

    }
}

class MyThread2 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i % 2 != 0){
                System.out.println(Thread.currentThread().getName() + ":" + i);

            }
        }

    }
}

方式二:实现Runnable接口

在这里插入图片描述在这里插入图片描述

package cn.tedu.thread;

public class RunnableDemo {
    public static void main(String[] args) {
        //创建描述线程信息类的对象
        RDemo r = new RDemo();//Runnable接口的实现类对象

        //创建线程对象---Thread对象
        Thread t = new Thread(r);//装饰者设计模式
        //调用start方法来开启线程
        t.start();

        //主线程执行内容
        for (int i = 20; i >= 0; i--) {
            System.out.println("main:" + i);

            //线程休眠
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//定义类去描述线程的任务信息
class RDemo implements Runnable {
    //重写run方法指定线程的任务信息
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("run:" + i);

            //线程休眠
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

在这里插入图片描述

继承与实现方式的联系与区别

在这里插入图片描述

线程的生命周期

在这里插入图片描述

Thread类的有关方法

在这里插入图片描述
在这里插入图片描述

多线程并发安全问题的解决方案(加锁)

在这里插入图片描述

同步代码块锁

锁对象:
可以把当前参与的线程对象共享进来的对象
方法区资源(可以共享所有的线程对象)
this(前提是参与的线程对象共享同一个Runnable实现类对象)

创建四个售票员进行售票,每个售票员被一个线程装饰

package cn.tedu.thread;

public class SellTiccketDemo1 {
    public static void main(String[] args) {
        //创建代表票类的对象
        Ticket t = new Ticket();
        //设置剩余票数
        t.setCount(100);

        //创建Seller类的对象---代表四个售票员
        Seller s1 = new Seller(t);
        Seller s2 = new Seller(t);
        Seller s3 = new Seller(t);
        Seller s4 = new Seller(t);

        //创建四个线程对象(给线程对象指定名称)
        Thread t1 = new Thread(s1, "A");
        Thread t2 = new Thread(s2, "B");
        Thread t3 = new Thread(s3, "C");
        Thread t4 = new Thread(s4, "D");

        //开启线程
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}


//定义类---描述线程任务信息(卖票)
class Seller implements Runnable {

    //代表票数
    //int ticket=100;

    //声明代表票类的对象
    Ticket t;

    //有参构造(保证共卖100张票---保证创建的所有的Seller类的对象共享同一个Ticket类的对象)
    public Seller(Ticket t) {
        this.t = t;
    }

    //重写run方法---指定卖票的过程
    @Override
    public void run() {
        while (true) {//循环要执行但是不能写结束条件
            //同步代码块锁
            //代码块去包住线程的核心内容
            //()---锁对象(可以把线程对象共享进来的对象)【三种方式】
            //方式一:synchronized (t) {//可以把当前参与的所有线程对象共享进来
            //方式二:synchronized (String.class) {//Seller.class  Math.class   方法区资源(共享所有的线程对象)
            //方式三:synchronized (this) 前提是参与的线程对象共享同一个Runnable实现类对象
            synchronized (this) {//这个案例中不可以使用,this表示当前类对象,这个案例中有4个对象
                //结束循环的条件
                if (t.getCount() == 0)
                    break;
                //票数减一并且设置新的剩余票数
                t.setCount(t.getCount() - 1);
                //输出(当前正在使用的线程的对象名字)
                System.out.println(Thread.currentThread().getName() + "卖了一张票,还剩余" + t.getCount() + "张票。。。");
            }
        }
    }
}

//定义代表票的类
class Ticket {
    //属性
    private int count;//代表票数

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}


同步方法锁

在方法上加上 synchronized关键字来修饰方法,
会默认提供锁对象来共享线程对象,
共享进来的线程对象在执行方法内容时可以保证只能每次有一个线程对象来执行。

如果修饰的是非静态方法默认的锁对象是this
如果修饰的是静态方法默认的锁对象是当前类.class(方法区资源可以共享所有线程对象)

创建一个售票系统,分别用四个线程来修饰这个售票系统

package cn.tedu.thread;

public class SellTicketDemo2 {
    public static void main(String[] args) {
        //创建代表票类的对象
        Ticket t = new Ticket();
        //设置剩余票数
        t.setCount(100);

        //创建Seller类的对象---代表一个售票系统
        Seller1 s = new Seller1(t);//Runnable实现类的对象


        //创建四个线程对象(给线程对象指定名称)
        //参与的线程对象共享同一个Runnable实现类的对象
        Thread t1 = new Thread(s, "A");
        Thread t2 = new Thread(s, "B");
        Thread t3 = new Thread(s, "C");
        Thread t4 = new Thread(s, "D");

        //开启线程
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

//定义类---描述线程任务信息(卖票)
class Seller1 implements Runnable {

    //代表票数
    //int ticket=100;

    //声明代表票类的对象
    Ticket t;

    //有参构造(保证共卖100张票---保证创建的所有的Seller类的对象共享同一个Ticket类的对象)
    public Seller1(Ticket t) {
        this.t = t;
    }

    //重写run方法---指定卖票的过程
    //同步方法锁如果锁住的是非静态方法默认的锁对象是this
    //同步方法锁如果锁住的是静态方法默认的锁对象是当前类.class
    @Override
    //这个run方法运行结果只能保证一个线程进入run,然后全部卖完。
    public synchronized void run() { //同步方法锁默认的锁对象就是this
        while (true) {//循环要执行但是不能写结束条件
            //同步代码块锁
            //代码块去包住线程的核心内容
            //()---锁对象(可以把线程对象共享进来的对象)
            //synchronized (t) {//可以把当前参与的所有线程对象共享进来
            //synchronized (String.class) {//Seller.class  Math.class   方法区资源(共享所有的线程对象)
            //synchronized (this) {
            //结束循环的条件
            if (t.getCount() == 0)
                break;
            //票数减一并且设置新的剩余票数
            t.setCount(t.getCount() - 1);
            //输出(当前正在使用的线程的对象名字)
            System.out.println(Thread.currentThread().getName() + "卖了一张票,还剩余" + t.getCount() + "张票。。。");
            //}
        }
    }
}

在这里插入图片描述

死锁

package cn.tedu.thread;

public class DeadLockDemo {
    //创建静态对象
    private static Printer p=new Printer();
    private static Scaner s=new Scaner();

    public static void main(String[] args) {
        //表示第一个员工(先打印再扫描)
        new Thread(new Runnable() {
            @Override
            public void run() {
                //先打印
                synchronized (p){
                    p.print();
                    //休眠
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //在扫描
                    synchronized (s){
                        s.scan();
                    }
                }
            }
        }).start();
        //第二个员工(先扫描再打印)
        new Thread(new Runnable() {
            @Override
            public void run() {
                //先扫描
                synchronized (s){
                    s.scan();
                    //休眠
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //再打印
                    synchronized (p){
                        p.print();
                    }
                }
            }
        }).start();
    }
}



//定义代表打印机的类
class Printer{
    public void print(){
        System.out.println("在哼哧哼哧打印。。。");
    }
}
//定义代表扫描仪的类
class Scaner{
    public void scan(){
        System.out.println("在呼哧呼哧的扫描。。。");
    }
}

class demo{
    private int count;


}

生产者消费者(各一个)

package cn.tedu.thread;

public class WaitNotifyDemo {
    public static void main(String[] args) {
        //创建代表商品类的对象
        Productor p=new Productor();
        //开启线程
        new Thread(new Producer(p)).start();
        new Thread(new Consumer(p)).start();
    }
}



//定义类描述线程的任务信息---生产
class Producer implements Runnable{
    //声明代表商品的类的对象
    private Productor p;

    //有参构造(保证共享同一个商品类的对象)
    public Producer(Productor p){
        this.p=p;
    }

    @Override
    public void run() {
        //死循环
        while (true) {
            synchronized (p) {

                //线程等待
                if(p.getFlag()==true)//flage默认为false,要想让生产者先走,就不能进这个判断,否者就会挂起
                try {
                    p.wait();//令当前线程挂起并放弃CPU、同步资源并等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //生产的最大值
                int max = 1000 - p.getCount();
                //随机生产商品(0~max可以取到max的值)
                int count = (int) (Math.random() * (max + 1));
                //设置最新的剩余商品数量
                p.setCount(p.getCount() + count);
                //输出
                System.out.println( "生产者生产了" + count + "个商品还剩余" +
                        p.getCount() + "个商品。。。");

                //唤醒等待的线程对象
                p.notify();
                //改变布尔值
                p.setFlag(true);
            }
        }
    }
}

//定义类描述线程的任务信息---消费
class Consumer implements Runnable{
    //声明代表商品的类的对象
    private Productor p;

    //有参构造(保证共享同一个商品类的对象)
    public Consumer(Productor p){
        this.p=p;
    }
    @Override
    public void run() {
        //死循环
        while (true){
            synchronized (p){
                if(p.getFlag()==false)
                //线程等待
                try {
                    p.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //消费的随机商品数量(0~p.getCount()  取到最大值)
                int count=(int)(Math.random()*(p.getCount()+1));
                //设置最新的商品剩余数量
                p.setCount(p.getCount()-count);
                //输出
                System.out.println( "消费者消费了" + count + "个商品还剩余" +
                        p.getCount() + "个商品。。。");

                //唤醒等待的线程对象
                p.notify();
                //改变布尔值
                p.setFlag(false);

            }
        }
    }
}


//定义代表商品的类
class Productor{
    //属性
    private int count;//代表商品数量

    //标志位
    private boolean flag;//默认值false

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public boolean getFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}

在这里插入图片描述
在这里插入图片描述

生产者消费者(多个NotifyAll)

package cn.tedu.thread;

public class WaitNotifyAllDemo {
    public static void main(String[] args) {
        //创建代表商品类的对象
        Productor p=new Productor();
        //开启线程
        new Thread(new Producer1(p)).start();
        new Thread(new Producer1(p)).start();
        new Thread(new Producer1(p)).start();
        new Thread(new Consumer1(p)).start();
        new Thread(new Consumer1(p)).start();
        new Thread(new Consumer1(p)).start();
    }
}
//定义类描述线程的任务信息---生产
class Producer1 implements Runnable{
    //声明代表商品的类的对象
    private Productor p;

    //有参构造(保证共享同一个商品类的对象)
    public Producer1(Productor p){
        this.p=p;
    }

    @Override
    public void run() {
        //死循环
        while (true) {
            synchronized (p) {

                //线程等待
                while (p.getFlag()==true)//语法是每次都需要判断
                    try {
                        p.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                //生产的最大值
                int max = 1000 - p.getCount();
                //随机生产商品(0~max可以取到max的值)
                int count = (int) (Math.random() * (max + 1));
                //设置最新的剩余商品数量
                p.setCount(p.getCount() + count);
                //输出
                System.out.println( "生产者生产了" + count + "个商品还剩余" +
                        p.getCount() + "个商品。。。");

                //唤醒等待的线程对象(随机唤醒)
                //p.notify();
                //唤醒所有等待的线程对象
                p.notifyAll();
                //改变布尔值
                p.setFlag(true);
            }
        }
    }
}

//定义类描述线程的任务信息---消费
class Consumer1 implements Runnable{
    //声明代表商品的类的对象
    private Productor p;

    //有参构造(保证共享同一个商品类的对象)
    public Consumer1(Productor p){
        this.p=p;
    }
    @Override
    public void run() {
        //死循环
        while (true){
            synchronized (p){
                while (p.getFlag()==false)
                    //线程等待
                    try {
                        p.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                //消费的随机商品数量(0~p.getCount()  取到最大值)
                int count=(int)(Math.random()*(p.getCount()+1));
                //设置最新的商品剩余数量
                p.setCount(p.getCount()-count);
                //输出
                System.out.println( "消费者消费了" + count + "个商品还剩余" +
                        p.getCount() + "个商品。。。");

                //唤醒等待的线程对象(随机唤醒)
                //p.notify();
                //唤醒所有等待的线程对象
                p.notifyAll();

                //改变布尔值
                p.setFlag(false);

            }
        }
    }
}

wait() 与 与 notify() 和 和 notifyAll()

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

sleep方法和wait方法

在这里插入图片描述

优先级

在这里插入图片描述

package cn.tedu.thread;

public class PriorityDemo {
    public static void main(String[] args) {
        //创建线程对象
        Thread t1=new Thread(new PDemo(),"A");
        Thread t2=new Thread(new PDemo(),"B");

        //设置优先级
        t1.setPriority(1);
        t2.setPriority(10);//10的优先级比1大

        //开启线程
        t1.start();
        t2.start();
    }
}

//代表线程任务信息
class PDemo implements Runnable{
    @Override
    public void run() {
        for(int i=0;i<=30;i++){
            System.out.println(Thread.currentThread().getName()+":"+i);

            //休眠
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

在这里插入图片描述

守护线程

在这里插入图片描述

package cn.tedu.thread;

public class DeamonDemo {
    public static void main(String[] args) {
        //创建线程对象
        Thread t1=new Thread(new Soilder(),"超级兵");
        Thread t2=new Thread(new Soilder(),"宫本");
        Thread t3=new Thread(new Soilder(),"炮车");
        Thread t4=new Thread(new Soilder(),"花木兰");

        //设置守护线程
        t1.setDaemon(true);
        t2.setDaemon(true);
        t3.setDaemon(true);
        t4.setDaemon(true);

        //开启线程
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        //只要不是守护线程的就一定是被守护线程
        //主线程---BOSS(被守护线程)
        for(int i=10;i>=0;i--){
            System.out.println("BOOS掉了一滴血还剩" + i + "滴血。。。");
            //休眠
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}


//定义类代表小兵
class Soilder implements Runnable{
    @Override
    public void run() {
        for (int i = 20; i >= 0; i--) {
            //描述小兵掉血过程
            System.out.println(Thread.currentThread().getName() + "掉了一滴血还剩" + i + "滴血。。。");

            //休眠
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sparky*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值