synchronized run()方法

来源:互联网 发布:云计算技术 2016 编辑:程序博客网 时间:2024/06/07 03:52

最近编程有一个需求,需要某个线程只能有一个run()方法在执行,然后自然而然想到了用synchronized修饰run()方法来解决这个问题,详细代码如下:

  1. public class VolatileThread extends Thread {  
  2.   
  3.     public synchronized void run() {  
  4.         for (int i = 0; i < 10; i++) {  
  5.             System.out.println(Thread.currentThread().getName());  
  6.         }  
  7.     }  
  8.   
  9.     public static void main(String[] args) {  
  10.         for (int i = 0; i < 3; i++) {  
  11.             VolatileThread vt = new VolatileThread();  
  12.             //设置线程的名称,看在执行哪个对象的run()  
  13.             vt.setName(i + "");  
  14.             vt.start();  
  15.         }  
  16.     }  
  17. }  

     但是最终的执行结果还是同时会有多个线程在执行run()中的代码,然后百思不得其解,想了很久,才发现问题所在。在方法上加synchronized等同于synchronized(this),虽然看似给run()方法加上了锁,但是我们看main()中是如何去产生多个线程的,是分别new出了三个不同的线程对象。也就是说三个线程都拿到各自对象的锁,因此都能够执行run()中的代码。要解决这个问题其中一个方法是通过runnable接口来实现线程,详细代码如下:

  1. public class VolatileThread implements Runnable {  
  2.   
  3.     public synchronized void run() {  
  4.         for (int i = 0; i < 10; i++) {  
  5.             System.out.println(Thread.currentThread().getName());  
  6.         }  
  7.     }  
  8.   
  9.     public static void main(String[] args) {  
  10.         VolatileThread vt = new VolatileThread();  
  11.         for (int i = 0; i < 3; i++) {  
  12.             Thread td = new Thread(vt);  
  13.             //设置线程的名称,看在执行哪个对象的run()  
  14.             td.setName(i + "");  
  15.             td.start();  
  16.         }  
  17.     }  
  18. }  


0 0
原创粉丝点击