Java(89):解决多线程安全—synchronized(2)

https://blog.csdn.net/fen_fen/article/details/122392800 遇到线程不安全问题

Java(89):解决多线程安全—synchronized(2) 

解决方法:使用synchronized

解析可参考:https://blog.csdn.net/fen_fen/article/details/121466128

1、synchronized代码块,代码示例

package runnable;
// 定义一个实现了 Runnable 接口的类
class RunnableTest4  implements Runnable{
    private int ticket =10;
    private boolean flag=true;
    // 重写run方法,实现自己的业务逻辑
    @Override
    public void run() {
        int allTicket=ticket;
        while (flag){
            try{
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized(this) {
                if (this.ticket > 0) {
                    System.out.println("票号:" + ticket-- + ",已被售卖,售卖窗口:" + Thread.currentThread().getName());
                }
                else {
                    flag=false;
                    System.out.println(allTicket+"票已被卖完,当前咨询窗口:" + Thread.currentThread().getName());
                }
            }

        }

    }
}

public class RunnableDemo4 {
    public static void main(String[] args){
        //创建Runnable 对象
        RunnableTest4 rt=new RunnableTest4();
        // 将一个 Runnable对象作为Thread的构造参数
        //调用Thread对象的 start 方法,注意不能调用 run 方法
        Thread thread1=new Thread(rt,"1号窗口");
        Thread thread2=new Thread(rt,"2号窗口");
        Thread thread3=new Thread(rt,"3号窗口");
        thread1.start();
        thread2.start();
        thread3.start();

    }
}

执行结果:

Java(89):解决多线程安全—synchronized(2)

  2、synchronized方法代码示例

synchronized void method() {//业务代码}

package runnable;
// 定义一个实现了 Runnable 接口的类
class RunnableTest4  implements Runnable{
    private int ticket =10;
    private boolean flag=true;
    // 重写run方法,实现自己的业务逻辑
    @Override
    public void run() {
        while (flag){
            try{
                Thread.sleep(500);
                sell();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    synchronized private void sell(){
        int allTicket=ticket;
        if (this.ticket > 0) {
            System.out.println("票号:" + ticket-- + ",已被售卖,售卖窗口:" + Thread.currentThread().getName());
        }
        else {
            flag=false;
            System.out.println(allTicket+"票已被卖完,当前咨询窗口:" + Thread.currentThread().getName());
        }
    }
}

public class RunnableDemo4 {
    public static void main(String[] args){
        //创建Runnable 对象
        RunnableTest4 rt=new RunnableTest4();
        // 将一个 Runnable对象作为Thread的构造参数
        //调用Thread对象的 start 方法,注意不能调用 run 方法
        Thread thread1=new Thread(rt,"1号窗口");
        Thread thread2=new Thread(rt,"2号窗口");
        Thread thread3=new Thread(rt,"3号窗口");
        thread1.start();
        thread2.start();
        thread3.start();

    }
}

执行结果:

Java(89):解决多线程安全—synchronized(2)

 

上一篇:RT-Thread移植入门学习


下一篇:线段树