首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

线程同步,一相奇怪的有关问题

2012-10-07 
线程同步,一相奇怪的问题Java codepackage com.synpublic class TT implements Runnable {int b 100pu

线程同步,一相奇怪的问题

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的过程中被其他线程抢占,因为被锁住了。

热点排行
Bad Request.