面试题。线程pingpong的输出问题


第一种情况:
public class Main { public static void main(String args[]) { Thread t = new Thread() { public void run() { pong(); } }; t.run(); System.out.println("ping"); } static void pong() { System.out.println("pong"); } }
输出:pingpong 解释:调用run()方法,整个程序只有一个线程,主线程,run()是Runnable接口中定义的一个方法,是为了让客户程序员在这个方法里写自己的功能代码的。直接调用和普通的类调用自己的成员方法是没有任何区别的。
第二种情况
public static void main(String args[]) {
        Thread t = new Thread() {
        public void run() {
        pong();
        }
        }; 
        t.start();
        
        System.out.println("ping");
        }
        static void pong() {
        System.out.println("pong");
        }
}
输出:pongping,解释:用start()方法之后,程序就会多出一个线程,设定新线程进入 “就绪” 状态,等待 CPU 调度之后才会执行
这时才有和主线程争cpu。
而下一个 System.out.print() 几乎(概率大于99%)可以认为是立即接着执行的。
所以,最终效果就是,几乎都是 pongping。
第三种情况

public class Test02 {
public static void main(String args[]) throws InterruptedException {
Thread mThread = Thread.currentThread();
Thread t = new Thread() {
public void run() {
try {
Thread.sleep(250);// 1.  这句话注释掉和不注释掉的区别,或者更改sleep里面时间的区别
} catch (InterruptedException e) {
e.printStackTrace();
}
pong();
}
};
t.start();// 换成t.run(),观察不同一般在笔试题中是陷阱,混淆start
mThread.sleep(250);// 2.  这句话注释掉和不注释掉的区别,或者更改sleep里面时间的区别
System.out.println("ping");
}

static void pong() {
System.out.println("pong");
}

}

输出pingpong和pongping都有可能

原文地址:https://www.cnblogs.com/wangqingming/p/10695074.html