开发者社区 问答 正文

JAVA加锁过程中遇到的问题

public class TextSync implements Runnable {
    /**
     * @Vesine
     * 多线程锁问题程序
     * 2014年12月23日15:47:32
     */
    Timer timer=new Timer();
    public static void main(String[] args) {
        Thread t1=new Thread(new TextSync());
        Thread t2=new Thread(new TextSync());
        t1.setName("MY Thread1");
        t2.setName("MY Thread2");
        t1.start();
        t2.start();
    }
    public void run(){
        timer.add(Thread.currentThread().getName());

    }
}
public class Timer {
    private static int num=0;
    public synchronized void add(String name){
        num++;
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {

            e.printStackTrace();
        }
        System.out.println(name+":你是第"+num+"个访问线程");
    }
}

为什么加锁后程序运行结果仍为
MY Thread1:你是第2个访问线程
MY Thread2:你是第2个访问线程

展开
收起
蛮大人123 2016-02-28 18:26:32 2111 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    synchronized 修饰方法时
    “同时只能有一个线程访问当前方法”针对的是同一个对象。
    你的例子里,每个TextSync 都new了自己的Timer,不是同一个对象,synchronized 修饰的方法同一时间只有自己的TextSync会访问,所以根本不存在锁竞争。
    你这个是多个线程跑各自的Timer,可以修改成如下:

    public class TextSync implements Runnable {
    
        /**
         * @Vesine
         * 多线程锁问题程序
         * 2014年12月23日15:47:32
         */
        Timer timer=new Timer();
        public static void main(String[] args) {
            Thread t1=new Thread(new TextSync());
            Thread t2=new Thread(new TextSync());
            t1.setName("MY Thread1");
            t2.setName("MY Thread2");
            t1.start();
            t2.start();
    
        }
        public void run(){
            timer.add(Thread.currentThread().getName());
    
        }
    }
    class Timer {
        private static int num=0;
        public void add(String name){
            synchronized(Timer.class) {
    
                num++;
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
    
                    e.printStackTrace();
                }
                System.out.println(name + ":你是第" + num + "个访问线程");
            }
        }
    }
    2019-07-17 18:49:58
    赞同 展开评论
问答分类:
问答地址: