Java多线程之synchronized线程锁
2021-06-22 02:05
标签:tick span ase als [] app tap oid art Java多线程之synchronized线程锁 标签:tick span ase als [] app tap oid art 原文地址:https://www.cnblogs.com/gongxr/p/9680871.html 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 ) {
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 }
上一篇:Python基础-09-内置函数
下一篇:springboot-多环境测试
文章标题:Java多线程之synchronized线程锁
文章链接:http://soscw.com/index.php/essay/97170.html