Day64.线程的生命周期、线程同步的两种方法实现 -Java多线程

线程的生命周期

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m7fOcMkO-1602074863111)(C:\Users\PePe\AppData\Roaming\Typora\typora-user-images\image-20201007152149277.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bPoXgflt-1602074863114)(C:\Users\PePe\AppData\Roaming\Typora\typora-user-images\image-20201007154731960.png)]

线程同步的两种方法实现

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9rgqicjj-1602074863117)(C:\Users\PePe\AppData\Roaming\Typora\typora-user-images\image-20201007163933179.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-t4ShQlyF-1602074863122)(C:\Users\PePe\AppData\Roaming\Typora\typora-user-images\image-20201007180112778.png)]

方式一: 同步代码块

方式一: 同步代码块 使用实现Runnable接口的方式

/**
 * 创建三个窗口,总票数为100张,使用实现Runnable接口的方式
 * 存在线程安全问题,待解决。
 *
 *  1. 卖票过程中,出现了重票、错票  --->线程安全问题
 *  2. 问题出现的原因: 当某个线程操作车票的过程中,尚未操作完成时,其他线程参与进来,也来操作车票。
 *  3. 如何解决: 当一个线程在操作ticket的时候,其他线程不能参与进来。直到线程A操作完ticket时
 *              其他线程才可以开始操作ticket。这种情况即是线程A出现了阻塞,也不能被改变。
 *  4. 在Java中,我们通过同步机制,来解决线程的安全问题。
 *
 *      方式一: 同步代码块
 *
 *          synchronized(同步监视器){
 *               //需要被同步的代码
 *
 *           }
 *          说明: 1. 操作共享数据的代码,即为需要被同步的代码  -->不能包含代码多了,也不能包含代码少了。
 *               2. 共享数据: 多个线程共同操作的变量。比如: ticket就是共享数据
 *               3. 同步监视器,俗称: 锁。任何一个类的对象,都可以充当锁。
 *                   要求: 多个线程必须要共用同一个把锁。
 *
 *                   补充: 在实现Runnable接口创建多线程的方式中,我们可以考虑,使用this充当同步监视器。
 *
 *
 *      方拾二: 同步方法
 *
 *  5. 同步的方式,解决了线程的安全问题。 --->好处
 *     操作同步代码时,只能有一个线程参与,其他线程等待。相当于是一个单线程的过程,效率低。 --->局限性
 *
 * @author 阿昌
 * @create 2020-10-07 11:27
 */

class WThread implements Runnable {
    private int ticket = 100;
    Object obj = new Object();

    @Override
    public void run() {
        while (true) {
            synchronized (this) {   //synchronized (obj) {
                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + " 卖票,票号为: " + ticket);
                    ticket--;
                } else {
                    break;
                }
            }

        }
    }

    public static class WindowTest1 {
        public static void main(String[] args) {
            WThread wThread = new WThread();

            Thread t1 = new Thread(wThread);
            Thread t2 = new Thread(wThread);
            Thread t3 = new Thread(wThread);

            t1.setName("窗口1");
            t2.setName("窗口2");
            t3.setName("窗口3");


            t1.start();
            t2.start();
            t3.start();


        }
    }
}
方式一: 同步代码块 使用继承Thread类的方式实现

/**例子:
 * 创建三个窗口,总票数为100张,使用继承Thread类的方式实现
 *
 * 存在线程安全问题,待解决。
 * ↓  ↓  ↓  ↓  ↓  ↓
 * 使用同步代码块来解决继承Thread类的方式的线程安全问题
 *
 * 说明: 在继承Thread类创建多线程的方式中,慎用this充当同步监视器。考虑使用当前类充当同步监视器。
 *
 * @author 阿昌
 * @create 2020-10-07 10:09
 */

class Window extends Thread{

    private static int ticket = 100;
    static Object obj =new Object();

    @Override
    public void run() {
        while (true){
            //错误的方式: this代表的t1,t2,t3三个对象
            //synchronized(this){
            //正确的
//          synchronized(obj){
            synchronized(Window.class){ //Class clazz = Window.class;Window.class只会加载一次


            if (ticket> 0){

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(getName() + ": 买票,票号为: "+ ticket);
                ticket--;
            }else{
                System.out.println(getName() + "票已售空");
                break;
            }
            }
        }
    }
}



public class WindowTest {
    public static void main(String[] args) {
        Window w1 = new Window();
        Window w2 = new Window();
        Window w3 = new Window();

        w1.setName("窗口1");
        w2.setName("窗口2");
        w3.setName("窗口3");

        w1.start();
        w2.start();
        w3.start();
    }
}

方式二: 同步方法

方式二: 同步方法 实现Runnable接口

/**
 * 使用 同步方法 解决实现Runnable接口的线程安全问题
 *
 * 关于同步方法的总结:
 *  1. 同步方法仍然涉及到同步监视器,只是不需要我们显示的声明。
 *  2. 非静态的同步方法,同步监视器是: this
 *     静态的同步方法,同步监视器是: 当前类本身
 *  
 *
 * @author 阿昌
 * @create 2020-10-07 19:10
 */
class WThread2 implements Runnable {
    private int ticket = 100;
    @Override
    public void run() {
        while (ticket > 0) {

            show();
        }

    }

    private synchronized void show(){// 同步监视器: this
        if (ticket > 0) {

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName() + " 卖票,票号为: " + ticket);
            ticket--;

        }
    }
}


    public class WindowTest2 {
        public static void main(String[] args) {
            WThread2 wThread2 = new WThread2();

            Thread t1 = new Thread(wThread2);
            Thread t2 = new Thread(wThread2);
            Thread t3 = new Thread(wThread2);

            t1.setName("窗口1");
            t2.setName("窗口2");
            t3.setName("窗口3");


            t1.start();
            t2.start();
            t3.start();

        }
    }
方式二: 同步方法 继承Thread类

/**
 * 使用 同步方法 来解决继承Thread类实现多线程安全问题
 * @author 阿昌
 * @create 2020-10-07 19:48
 */
class Window3 extends Thread{

    private static int ticket = 100;

    @Override
    public void run() {
        while (true){

            show();

        }
    }
        private static synchronized void show(){//同步监视器: Window3.class
        //private  synchronized void show(){//同步监视器:this: w1,w2,w3。此种解决方法是错误的
            if (ticket> 0){

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + ": 买票,票号为: "+ ticket);
                ticket--;

            }
        }
    }



public class WindowTest3 {
    public static void main(String[] args) {
        Window3 w1 = new Window3();
        Window3 w2 = new Window3();
        Window3 w3 = new Window3();

        w1.setName("窗口1");
        w2.setName("窗口2");
        w3.setName("窗口3");

        w1.start();
        w2.start();
        w3.start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

阿昌喜欢吃黄桃

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

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

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

打赏作者

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

抵扣说明:

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

余额充值