标签:运行 法则 time mil strong sleep get 关键字 方法
1、synchronized 同步方法:
package com.test; public class TestObject { synchronized public void methodA() { try { System.out.println("begin methodA threadName=" + Thread.currentThread().getName() + " beigin time = " + System.currentTimeMillis()); Thread.sleep(1000); System.out.println("end methodA endTime=" + System.currentTimeMillis()); } catch (Exception e) { e.printStackTrace(); } } public void methodB() { try { System.out.println("begin methodB threadName=" + Thread.currentThread().getName() + " beigin time = " + System.currentTimeMillis()); Thread.sleep(1000); System.out.println("end methodB endTime=" + System.currentTimeMillis()); } catch (Exception e) { e.printStackTrace(); } } }
package com.test; public class Run { public static void main(String[] args) { TestObject object = new TestObject(); Thread a = new Thread(new Runnable() { @Override public void run() { object.methodA(); } }); Thread b = new Thread(new Runnable() { @Override public void run() { object.methodB(); } }); a.start(); b.start(); } }
运行结果: begin methodA threadName=Thread-0 beigin time = 1527756573018 begin methodB threadName=Thread-1 beigin time = 1527756573018 end methodB endTime=1527756574018 end methodA endTime=1527756574018
通过上面的代码可以得知,虽然线程A先蚩尤了object对象的锁,但是线程B完全可以异步调用非synchronized类型的方法。
如果将TestObject.java 中的methodB()方法前加上synchronized关键字。
#methodB()前加synchronized关键字运行结果: begin methodA threadName=Thread-0 beigin time = 1527756647320 end methodA endTime=1527756648321 begin methodB threadName=Thread-1 beigin time = 1527756648321 end methodB endTime=1527756649321
结论:
标签:运行 法则 time mil strong sleep get 关键字 方法
原文地址:https://www.cnblogs.com/gouge/p/9117628.html