public class TT implements Runnable{
int b = 100;
public synchronized void m1() throws Exception{
b = 1000;
Thread.sleep(5000);
System.out.println("b = "+b);
}
public synchronized void m2() throws Exception{
Thread.sleep(2500);
b = 2000;
}
public void run(){
try{
m1();
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception{
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
tt.m2();
}
}以上代码运行结果:
D:\java>javac TT.java
D:\java>java TT
b = 1000我的理解是:当线程t执行到m1()时先把b的值改为1000,然后进程sleep状态,接着主线程调用m2(),m2()休眠2500率先醒过来,而后把b的值改成2000了,所以我不懂结果为什么是1000,小弟初学,对同步问题不是很懂,请大家帮帮忙,解析一下,在此先说声谢谢了...
int b = 100;
public synchronized void m1() throws Exception{
b = 1000;
Thread.sleep(5000);
System.out.println("b = "+b);
}
public synchronized void m2() throws Exception{
Thread.sleep(2500);
b = 2000;
}
public void run(){
try{
m1();
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception{
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
tt.m2();
}
}以上代码运行结果:
D:\java>javac TT.java
D:\java>java TT
b = 1000我的理解是:当线程t执行到m1()时先把b的值改为1000,然后进程sleep状态,接着主线程调用m2(),m2()休眠2500率先醒过来,而后把b的值改成2000了,所以我不懂结果为什么是1000,小弟初学,对同步问题不是很懂,请大家帮帮忙,解析一下,在此先说声谢谢了...
int b = 100; public synchronized void m1() throws Exception {
System.out.println("m1 started!!");
b = 1000;
Thread.sleep(5000);
System.out.println("m1's b = " + b);
} public synchronized void m2() throws Exception {
Thread.sleep(2500);
b = 2000;
System.out.println("m2's b = " + b);
} public void run() {
try {
m1();
} catch (Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) throws Exception {
TT tt = new TT();
Thread t = new Thread(tt);
t.start(); tt.m2();
}
}
Thread.sleep(1);
tt.m2();
看看这个
改成下面这样应该就可以了:public class Demo implements Runnable{
private int b = 100;
// private static Boolean flag = true;
public synchronized void m1() throws Exception{
b = 1000;
// Thread.sleep(5000);
this.wait();
System.out.println("b = "+b);
}
public synchronized void m2() throws Exception{
// Thread.sleep(2500);
b = 2000;
this.notifyAll();
}
public void run(){
try{
m1();
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception{
Demo tt = new Demo();
Thread t = new Thread(tt);
t.start();
Thread.sleep(1000);
tt.m2();
}
}