- Java code
package com.syn;public class TT implements Runnable { int b = 100; public static void main(String[] args) throws Exception { TT t = new TT(); Thread t1 = new Thread(t); t1.start(); t.m2(); Thread.sleep(6000); System.out.println("m2" +" :" +t.b); } @Override public void run() { try { m1(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized void m1() throws Exception { b = 1000; Thread.sleep(5000); System.out.println("m1" +" :" +b); } public synchronized void m2() throws InterruptedException { Thread.sleep(1000); b = 2000; System.out.println("m2" +" :" +b); }}
为什么 最后输出的是1000??,在线程2的时候应该已经改了的呀?
------解决方案--------------------------------------------------------
由于加了synchronized关键字, 所以只需要考虑是m1先被执行还是m2先被执行。里面的那些sleep都是浮云,不会在sleep的过程中被其他线程抢占,因为被锁住了。