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(); } }

  • 相关阅读:
    [one day one question] safari缓存太厉害
    对工厂方法模式的一些思考(2)
    对工厂方法模式的一些思考(java语法表示)
    [选译]MySQL5.7以上Zip版官方安装文档
    clojure 使用阿里云仓库
    对jbox2d引擎的一些回顾与思考(swing实现demo)
    定位
    空白空间及溢出的处理
    BFC
    高度自适应
  • 原文地址:https://www.cnblogs.com/u0mo5/p/3973753.html
Copyright © 2011-2022 走看看