zoukankan      html  css  js  c++  java
  • JAVA培训—线程同步--卖票问题

    线程同步方法:

    (1)、同步代码块,格式: synchronized (同步对象){ //同步代码 }

    (2)、同步方法,格式: 在方法前加synchronized修饰 问题: 多个人同时买票。

    1、资源没有同步。 package thread; public class Tickets implements Runnable { private int count = 5; @Override public void run() { for (int i = 0; i < 10; ++i) { if (count > 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(count--); } } } public static void main(String[] args) { Tickets tickets=new Tickets(); Thread t1=new Thread(tickets); Thread t2=new Thread(tickets); Thread t3=new Thread(tickets); t1.start(); t2.start(); t3.start(); } } 运行结果: 5 3 4 2 2 1 很明显结果是错的。

    2、同步代码块 run方法中进行同步,也就是对共享资源(票数、count)进行同步 package thread; public class Tickets implements Runnable { private int count = 5; @Override public void run() { for (int i = 0; i < 10; ++i) { synchronized (this) { if (count > 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(count--); } } } } public static void main(String[] args) { Tickets tickets = new Tickets(); Thread t1 = new Thread(tickets); Thread t2 = new Thread(tickets); Thread t3 = new Thread(tickets); t1.start(); t2.start(); t3.start(); } }

    3、同步方法 package thread; public class Tickets implements Runnable { private int count = 5; @Override public void run() { for (int i = 0; i < 10; ++i) { sale(); } } public synchronized void sale() { if (count > 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(count--); } } public static void main(String[] args) { Tickets tickets = new Tickets(); Thread t1 = new Thread(tickets); Thread t2 = new Thread(tickets); Thread t3 = new Thread(tickets); t1.start(); t2.start(); t3.start(); } }

  • 相关阅读:
    Java 线程池
    Java 内存模型
    img图片铺满父元素
    element-ui 表单复杂数据类型校验
    element-ui 栅格布局 一行五等分
    element-ui表单只验证单个字段
    记录
    js-字符串全局替换
    vue3-搭建项目-vue2-vu3使用上的变化
    小程序引入echarts
  • 原文地址:https://www.cnblogs.com/u0mo5/p/3973753.html
Copyright © 2011-2022 走看看