public class sync2 implements Runnable{
public static int num = 177; @Override
public void run() {
try {
add1();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
public void add1() throws InterruptedException
{
num = 400;
Thread.sleep(3000); System.out.println(num);
}
public void add2() throws InterruptedException
{
num = 300;
System.out.println(num);
}
}-----------------------------------------
public class test2 {
public static void main(String[] args) throws InterruptedException {
sync2 s2 = new sync2();
Thread t1 = new Thread(s2);
t1.start();
s2.add2(); }
}--------------------------------------------
请问结果为甚么是300 400 而不是300 300?明明在add2()方法中num值被修改为300,add1()中线程被唤醒后直接就进行了打印,为什么是400呢?
public static int num = 177; @Override
public void run() {
try {
add1();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
public void add1() throws InterruptedException
{
num = 400;
Thread.sleep(3000); System.out.println(num);
}
public void add2() throws InterruptedException
{
num = 300;
System.out.println(num);
}
}-----------------------------------------
public class test2 {
public static void main(String[] args) throws InterruptedException {
sync2 s2 = new sync2();
Thread t1 = new Thread(s2);
t1.start();
s2.add2(); }
}--------------------------------------------
请问结果为甚么是300 400 而不是300 300?明明在add2()方法中num值被修改为300,add1()中线程被唤醒后直接就进行了打印,为什么是400呢?
s2.add2()比 add1()更先执行。代码 不是放到前面就先执行的,你的add1是在线程中的,t1.start()并不保证就会马上运行。很大程度上后面的代码会比这个t1.start()运行的线程代码更快。这个不能100保证,取决于各种情况。