账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    多线程在run()方法上加同步无法保证线程同步
    42
    0

    问题描述

    1. 使用继承Thread方法创建线程实例
    2. 重写run()方法的时候,用synchronized关键字修饰run()方法
    3. 结果是线程之间不是同步进行,计算结果出现问题

    代码片段

    public class MyThreadDemo9 extends Thread{
        private static int count = 0;
        public String status;
        public MyThreadDemo9(String status){
            this.status = status;
        }
        @Override
        public synchronized void run() {
            for(int i = 0; i < 100; i++) {
                count++;
            }
        }
        public static void main(String[] args) throws InterruptedException {
            for(int i = 0; i < 100; i++) {
                MyThreadDemo9 m8 = new MyThreadDemo9("Thread status - " + i);
                m8.start();
            }
            Thread.sleep(3000);
            System.out.println(MyThreadDemo9.count);
        }
    }

    这个是什么原因呢,不能使用 synchronized 关键字修饰run()方法吗

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部