线程的同步

  • 线程同步机制同步块:Java中提供了同步机制,可以有效的防止资源冲突。同步机制使用 synchronized关键字 使用该关键字的代码块称为同步块。同步块 语法:
synchronized (Object){
}

同步块 实例:

public class Demo6  implements Runnable{
        int unm = 10;// 售票池 总票数

        public static void main(String[] args) {
            Demo6 demo6 = new Demo6();
            Thread thread1 = new Thread(demo6, "a1");// 一号售票机
            Thread thread2 = new Thread(demo6, "a2");// 二号售票机
            Thread thread3 = new Thread(demo6, "a2");// 三号售票机
            Thread thread4 = new Thread(demo6, "a4");// 四号售票机
            thread1.start();// 开启线程
            thread2.start();
            thread3.start();
            thread4.start();

        }

        @Override
        public void run() {
            while (true) {
                synchronized (this){// 同步代码块,加锁对象为自身
                if (unm > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("票数:" + unm--);
                }
            }
        }
    }
}

线程的同步
synchronized void name(){
}

Original: https://www.cnblogs.com/TeaTracing/p/16138365.html
Author: TeaTracing
Title: 线程的同步

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/622657/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球