由于synchronized代码块还有点疑惑,所以现在只谈谈synchronized方法。

1.synchronized针对的一个类的同一个实例而言的。如果是不同的实例,synchronized无用。

package com.icss.entity;

public class TestThread2 {

 /**
  * @param args
  */
 public static void main(String[] args) {
  MyThread thread1 = new MyThread();
  new Thread(thread1, "t1").start();
  new Thread(thread1, "t2").start();
 }

}

class MyThread implements Runnable{
 
 @Override
 public  void run() {
  // TODO Auto-generated method stub
  Operation op = new Operation();
  op.print();
 }
 
}

class Operation{
 public synchronized  void print(){
  try {
   int count = 5;
   while(count > 0){
    Thread.sleep(500);
    System.out.println(Thread.currentThread().getName()+"========="+count);
    count --;
   }
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

如果是上面的代码,因为是两个operation的实例,所以没有synchronized的效果。

修改如下代码:

class MyThread implements Runnable{
Operation op = new Operation();
@Override
public void run() {
// TODO Auto-generated method stub
op.print();
}

}

则可以有synchronized的效果。

 

另外,如果修改如下代码:

public static void main(String[] args) {
MyThread thread1 = new MyThread();

MyThread thread2 = new MyThread();
new Thread(thread1, "t1").start();
new Thread(thread2, "t2").start();
}
 class MyThread implements Runnable{

@Override
public synchronized void run() {
// TODO Auto-generated method stub
Operation op = new Operation();
op.print();
}

}

则不会对run()方法起到synchronized作用。因为两个线程对应的是两个不同的实现了Runnable接口的类的实例。

 

个人的一点拙见,欢迎拍砖。