synchronized run()方法

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

public synchronized void run() {  
    for (int i = 0; i < 10; i++) {  
        System.out.println(Thread.currentThread().getName());  
    }  
}  

public static void main(String[] args) {  
    for (int i = 0; i < 3; i++) {  
        VolatileThread vt = new VolatileThread();  
        //设置线程的名称,看在执行哪个对象的run()  
        vt.setName(i + "");  
        vt.start();  
    }  
}  

}

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

public class VolatileThread implements Runnable {

public synchronized void run() {  
    for (int i = 0; i < 10; i++) {  
        System.out.println(Thread.currentThread().getName());  
    }  
}  

public static void main(String[] args) {  
    VolatileThread vt = new VolatileThread();  
    for (int i = 0; i < 3; i++) {  
        Thread td = new Thread(vt);  
        //设置线程的名称,看在执行哪个对象的run()  
        td.setName(i + "");  
        td.start();  
    }  
}  

}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值