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

  • 相关阅读:
    windows下cmd命令行上传代码到github的指定库
    Navicat Premium 12.1.11.0安装与激活
    windows部署Apollo
    C#事件-使用事件需要的步骤
    C#委托和事件
    C#事件委托概念
    C#中委托和事件的区别
    C#委托与事件
    C#细说多线程
    C# 堆栈(Stack)和队列(Queue)
  • 原文地址:https://www.cnblogs.com/u0mo5/p/3973753.html
Copyright © 2011-2022 走看看