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

  • 相关阅读:
    RandomAccessFile类
    IO_ObjectOutputStream(对象的序列化)
    IO流_文件切割与合并(带配置信息)
    IO流_文件切割与合并
    IO流_SequenceInputStream(序列流)
    10-stack
    9-queue
    16-两种方法全排列
    8-全排列next_permutation
    15-Call to your teacher(有向图的连通判断)
  • 原文地址:https://www.cnblogs.com/u0mo5/p/3973753.html
Copyright © 2020-2023  润新知