当前位置: 代码迷 >> Java相关 >> 线程的一个小例子程序,不懂,求解答~
  详细解决方案

线程的一个小例子程序,不懂,求解答~

热度:91   发布时间:2016-04-22 20:58:52.0
线程的一个小例子程序,不懂,求解答~~在线等
package com.java.Thread;

public class tongbu2 implements Runnable{
int b = 100;

public synchronized void m1() throws Exception{
System.out.println("m1a");
b = 1000;
System.out.println("m1b");
//Thread.sleep(5000);
System.out.println("b(m1) = "+ b);
}

public void m2() throws Exception{
System.out.println("m2a");
b = 2000;
//System.out.println("m2b");
System.out.println("b(m2a) = "+ b);
System.out.println("m2b");

Thread.sleep(2000);
System.out.println("b(m2) = "+ b);
}

public void run(){
try{
m1();
}catch(Exception e){
e.printStackTrace();
}
}

public static void main(String[] args) throws Exception{
tongbu2 tb = new tongbu2();
Thread td = new Thread(tb);
td.start();

tb.m2();
//System.out.println("b(final)"+ tongbu2.b);
}
}
结果打印:
m2a
m1a
m1b
b(m2a) = 2000
b(m1) = 1000
m2b
b(m2) = 1000

------解决思路----------------------
引用:
Quote: 引用:

package com.java.Thread;

public class tongbu2 implements Runnable {
int b = 100;

public synchronized void m1() throws Exception {
System.out.println("m1修改b之前");
b = 1000;
System.out.println(b);
System.out.println("m1修改b之后");
//Thread.sleep(5000);
System.out.println("b(m1) = " + b);
}

public synchronized void m2() throws Exception {
System.out.println("m2修改b之前");
b = 2000;
System.out.println(b);
System.out.println("m2修改b之后");
//Thread.sleep(2000);
System.out.println("b(m2) = " + b);
}

public void run() {
try {
m1();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) throws Exception {
tongbu2 tb = new tongbu2();
Thread td = new Thread(tb);
td.start();
tb.m2();
}
}

建议楼主改成这样的代码,然后再一个个去掉synchronized关键字,查看运行结果,我想应该会有所得




去掉之后运行的结果能看的懂,就是加了synchronized 之后运行得到的这个结果看不懂,为什么不b(m2) = 1000 而不是2000那

B属于共享数据,m1,m2都在修改b的值,代码中有两个线程在运行,一个线程中运行m1,另一个线程中运行m2,如果没有synchronized修饰,这个方法不是同步方法,不出现2000的原因是线程运行的过程中被另一个线程侵占了资源,修改了b的值,而此时m2已经走过了b的赋值语句,要将b输出了。
  相关解决方案