码迷,mamicode.com
首页 > 编程语言 > 详细

Java多线程之synchronized线程锁

时间:2018-09-20 15:58:50      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:tick   span   ase   als   []   app   tap   oid   art   

 

 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 }

 

Java多线程之synchronized线程锁

标签:tick   span   ase   als   []   app   tap   oid   art   

原文地址:https://www.cnblogs.com/gongxr/p/9680871.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!