- <p>class Runs implements Runnable//实现接口
- {
- private int i=10;
- public void run(){//复写run()方法
- boolean flag=true;
- while(flag){
- synchronized(new Object()){//同步代码块
- if(i>0){
- try{Thread.sleep(10);}
- catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"--"+i--);
- }else
- flag=false;
- }
- }
- }
-
- };
- class Main
- {
- public static void main(String[] args){
- Runs run=new Runs();//建立Runnable子类对象
- Thread t1=new Thread(run);//将Runnable子类对象作为Thread的构造方法 建立对象
- Thread t2=new Thread(run);
- Thread t3=new Thread(run);
- Thread t4=new Thread(run);
-
- t1.start();
- t2.start();
- //t3.start();
- //t4.start();
- }
- };</p>
复制代码
我已经使用了同步机制,为什么 还会打印“0”呢?
|
|