zoukankan      html  css  js  c++  java
  • Java多线程(九) synchronized 锁对象的改变

    public class MyService {
    
        private String lock = "123";
    
        public void testMethod() {
            synchronized (lock) {
                System.out.println(ThreadB.currentThread().getName() + "begin " + System.currentTimeMillis());
                lock="456";
                try {
                    ThreadB.sleep(2000);
                    System.out.println(ThreadB.currentThread().getName() + "end " + System.currentTimeMillis());
                    
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        
    }

    锁lock从“123” 改为“456”

    ThreadA和ThreadB

    public class ThreadA extends Thread {
    
        private MyService myService;
    
        public ThreadA(MyService myService) {
            this.myService = myService;
        }
    
        public void run() {
            myService.testMethod();
        }
    }
    
    public class ThreadB extends Thread {
    
        private MyService myService;
    
        public ThreadB(MyService myService) {
            this.myService = myService;
        }
    
        public void run() {
            myService.testMethod();
        }
    }
    View Code

    Run

    public class Run {
    
        public static void main(String[] args) throws InterruptedException {
            MyService myService = new MyService();
            
            ThreadA threadA= new ThreadA(myService);
            threadA.start();
            Thread.sleep(50);
            ThreadA threadB= new ThreadA(myService);
            threadB.start();
            
        }
        
        
    }

    如果将Thread.sleep(50) 注释掉,A和B获取的锁都是“123”,虽然将锁改为“456”,结果还是同步的。

  • 相关阅读:
    Android学习笔记安卓基础知识
    V8编程1
    dfdf
    NodeJS沙箱
    CGI编程cgihtml库简析
    dsfdsf
    Android学习笔记获取屏幕大小
    Android学习笔记AndroidManifest.xml配置文件详解
    HTTP状态码解析
    简易c++版本日志库
  • 原文地址:https://www.cnblogs.com/newlangwen/p/7596416.html
Copyright © 2011-2022 走看看