synchronized关键字的使用简单实例

 1 package edu.thread.test;
 2 
 3 public class ThreadTest2 implements Runnable {
 4     @Override
 5     public void run() {
 6         getTicket();
 7     }
 8 
 9     /**
10      * 得到车票
11      */
12     private synchronized void getTicket() {
13         while (true) {
14             System.out.println(Thread.currentThread().getName());// 得到当前线程名称
15             try {
16                 Thread.currentThread().sleep(1000);// 睡眠
17             } catch (InterruptedException e) {
18                 // TODO Auto-generated catch block
19                 e.printStackTrace();
20             }
21         }
22     }
23 
24     public static void main(String[] args) {
25         ThreadTest2 test = new ThreadTest2();
26         // 新建线程启动购买车票
27         new Thread(test).start();
28         new Thread(test).start();
29         new Thread(test).start();
30         new Thread(test).start();
31         while (true) {
32             System.out.println("main....");
33             try {
34                 Thread.currentThread().sleep(1000);// 睡眠
35             } catch (InterruptedException e) {
36                 // TODO Auto-generated catch block
37                 e.printStackTrace();
38             }
39 
40         }
41     }
42 
43 }
44 /*
45  * 解释: synchronized方法是保持类的实例同时只能调用一次,直到方法运行结束才允许下一次调用。 但是如果
46  * synchronized方法存在睡眠或暂停,则将CPU给其他线程使用,但是期间还是持有该方法的锁, 任何调用该方法都将阻塞
47  */

运行结果:

运行结果分析:

synchronized方法是保持类的实例同时只能调用一次,直到方法运行结束才允许下一次调用。 

但是如果synchronized方法存在睡眠或暂停,则将CPU给其他线程使用,但是期间还是持有该方法的锁, 任何调用该方法都将阻塞

原文地址:https://www.cnblogs.com/afluy/p/3255248.html