- /*
- Sychronized:同步代码块,解决
- 问题是:这里为什么用到this会报错呢???
- */
- class Ticket implements Runnable
- {
- private static int ticket = 20;
- Object obj = new Object();
- public void run()
- {
- while(true)
- {
- synchronized(obj)
- {
- if(ticket>0)
- {
-
- System.out.println(this.getName()+"正在卖"+ticket-- +"号票");
-
- }
- }
- }
-
- }
-
- }
- class SynchronizedTest
- {
- public static void main(String[] args)
- {
- Ticket t = new Ticket(); //创建线程对象
- Thread t0 = new Thread(t); //创建线程
- Thread t1 = new Thread(t); //创建线程
- Thread t2 = new Thread(t); //创建线程
- Thread t3 = new Thread(t); //创建线程
-
- t0.start();
- t1.start();
- t2.start();
- t3.start();
- }
-
-
-
-
- }
- /*
- G:\代码>javac SynchronizedTest.java
- SynchronizedTest.java:22: 错误: 找不到符号
- System.out.println(this.getName()+"正在卖"+ticket-- +"
- 号票");
- ^
- 符号: 方法 getName()
- 1 个错误
- */
复制代码 |
|