锁定线程:同步方法

 1 package testBlog;
 2 
 3 class MyThread implements Runnable {
 4     private int ticket = 10;
 5 
 6     @Override
 7     public void run() {// 重点在此:要在覆写的run()方法中写上synchronized方法
 8         int x;
 9         for (x = 0; x < 20; x++) {// 执行20次sale()方法
10             this.sale();
11         }
12     }
13 
14     public synchronized void sale() {// synchronized处通常是static的位置啊.这是一个synchronized方法
15         if (ticket > 0) {
16             try {
17                 Thread.sleep(200);
18             } catch (InterruptedException e) {
19                 e.printStackTrace();
20             }
21             System.out.println(Thread.currentThread().getName() + "卖票,票数剩余:" + --ticket);//这里用前减减更合适
22         }
23     }
24 
25 }
26 
27 public class Test {
28     public static void main(String[] args) {
29         MyThread mt = new MyThread();
30         new Thread(mt, "票贩子A").start();
31         new Thread(mt, "票贩子B").start();
32         new Thread(mt, "票贩子C").start();
33 
34     }
35 }
原文地址:https://www.cnblogs.com/ssC2H4/p/8186743.html