synchronized run()方法的问题

来源:互联网 发布:unity3d 水波纹特效 编辑:程序博客网 时间:2024/06/05 19:32

昨天在看线程编程的时候,想到了了一个问题,就是给run方法加上synchronized能实现同步吗,所以就写了如下代码:

public class MyThread extends Thread {@Overridepublic synchronized void run() {// TODO Auto-generated method stubfor(int i=0; i<100; i++){System.out.println(Thread.currentThread().getName());}}public static void main(String[] args){for(int j=0; j<3; j++){
MyThread mt = new MyThread();mt.setName(Integer.valueOf(j).toString());mt.start();}}}
运行之后发现根本没有实现同步,还是几个线程在同时运行,查资料之后发现了问题所在,仔细观察new线程的代码:
MyThread mt = new MyThread();

在main函数里面它是通过for循环实现,实际上它是new出了不同的线程对象,也就是说其实每个MyThread对象都获得了各自的对象锁,都可以执行各自的run方法,解决办法是不去继承Thread类,通过实现runable接口的办法,实现代码如下:

public class MyThread implements Runnable {@Overridepublic synchronized void run() {// TODO Auto-generated method stubfor(int i=0; i<100; i++){System.out.println(Thread.currentThread().getName());}}public static void main(String[] args) throws InterruptedException {MyThread mt = new MyThread();for(int j=0; j<3; j++){Thread t = new Thread(mt);t.setName(Integer.valueOf(j).toString());t.start();}}}
这样就实现了对run方法的同步,因为建立的每个线程都是针对mt这同一个对象。

参考资料:http://www.cnblogs.com/yanhaidong/archive/2011/06/01/2339048.html



1 0
原创粉丝点击