import java.util.*;
public class TT implements Runnable{
public int i =100;
public synchronized void m1(){
i=1000;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("i="+i);
}
public void m2(){
i=2000;
System.out.println("i="+i);
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
m1();
}
public static void main(String [] args){
TT tt = new TT();
Thread tr=new Thread(tt);
tr.start();
tt.m2();
}
}
为什么会有三种输出结果?一种是2000,1000,一种是1000,1000,一种是2000,2000。第三种较少发生,求解释
public class TT implements Runnable{
public int i =100;
public synchronized void m1(){
i=1000;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("i="+i);
}
public void m2(){
i=2000;
System.out.println("i="+i);
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
m1();
}
public static void main(String [] args){
TT tt = new TT();
Thread tr=new Thread(tt);
tr.start();
tt.m2();
}
}
为什么会有三种输出结果?一种是2000,1000,一种是1000,1000,一种是2000,2000。第三种较少发生,求解释
又因为run执行完,线程也就结束了,自然不会有更多的打印,现在的两个打印分别是m1和m2中打印的,
明白了吧