zoukankan      html  css  js  c++  java
  • Java多线程之synchronized线程锁

     1 package org.study2.javabase.ThreadsDemo.sync;
     2 
     3 /**
     4  * @Auther:GongXingRui
     5  * @Date:2018/9/18
     6  * @Description:synchronized线程锁
     7  **/
     8 public class TicketApp {
     9     public static void main(String args[]) {
    10         Ticket ticket = new Ticket();
    11         Thread t1 = new Thread(ticket, "小红");
    12         Thread t2 = new Thread(ticket, "明明");
    13         t1.start();
    14         t2.start();
    15     }
    16 }
    17 
    18 class Ticket implements Runnable {
    19     int num = 20;
    20     private boolean flag = true;
    21 
    22     @Override
    23     public void run() {
    24         while (flag) {
    25             test();
    26         }
    27     }
    28 
    29     public synchronized void test() {
    30         if (num <= 0) {
    31             flag = false;
    32             return;
    33         }
    34         try {
    35             Thread.sleep(100);
    36         } catch (InterruptedException e) {
    37             e.printStackTrace();
    38         }
    39         System.out.println(Thread.currentThread().getName() + "抢到票:" + num--);
    40     }
    41 }
  • 相关阅读:
    sqlalchemy
    tornado-模板继承extend,函数和类的导入
    vi规范
    Spark 分布式SQL引擎
    Spark SQL 编程
    Spark SQL 基本原理
    spark SQL概述
    spark 多语言编程
    hadoop YARN
    spark 存储管理机制
  • 原文地址:https://www.cnblogs.com/gongxr/p/9680871.html
Copyright © 2011-2022 走看看