本帖最后由 quan23355 于 2013-11-27 21:25 编辑
同步锁对象为什么不能定义在run方法里面呢?
- class A implements Runnable{
- int i=10;
- Object obj=new Object();
- public void run() {
- synchronized (obj) {
-
- while(true){
- if(i>0){
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName()+":"+i--);
- }
-
- }
- }
- }
- }
- public class Test{
- public static void main(String[] args){
-
- A a=new A();
- Thread t=new Thread(a);
- Thread t1=new Thread(a);
- Thread t2=new Thread(a);
- Thread t3=new Thread(a);
-
- t.start();
- t1.start();
- t2.start();
- t3.start();
- }
- }
复制代码
|