本帖最后由 不去会死 于 2014-6-17 06:52 编辑
- class Ticket implements Runnable{
- static int ticket = 1000;
- Object obj = new Object();
-
- public void run() {
- while (ticket > 0){
- synchronized(obj){ //把synchronized放到while的外面
- try{Thread.sleep(10);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"ticket=" + ticket);
- --ticket;
- }
- }
- }
- }
- public class ThreadTest {
- public static void main(String[] args) {
- Ticket t = new Ticket();
- Thread t1 = new Thread(t);
- Thread t2 = new Thread(t);
- t1.start();
- t2.start();
- }
- }
复制代码 能不能将synchronized放到while的外面???为什么???
|