使用同步的线程顺序

Thread order using synchronized

有没有输出不是A/B/BC/AD(/是换行)的情况?第二个线程有可能先于第一个开始吗?

public class JavaApplication6 extends Thread{
final StringBuffer sb1 = new StringBuffer();
final StringBuffer sb2 = new StringBuffer();

public static void main(String[] args) throws InterruptedException {
    final JavaApplication6 h = new JavaApplication6();
    new Thread(){
        public void run(){
            synchronized(this){
                h.sb1.append("A");
                h.sb2.append("B");
                System.out.println(h.sb1);
                System.out.println(h.sb2);
            }
        }
    }.start();
    new Thread(){
        public void run(){
            synchronized(this){
                h.sb1.append("D");
                h.sb2.append("C");
                System.out.println(h.sb2);
                System.out.println(h.sb1);
            }
        }
    }.start();           
}}    

是的,第二个线程可以在第一个线程之前启动。

这可能是因为线程调度程序以不可预测的方式启动线程。

此外:由于线程之间的切换(由提到的线程调度程序进行),first 可以先开始,但最后结束。

即使您运行此应用程序多次'prove'该顺序将相同,也不能保证此顺序下次不会更改运行。

是的,第二个线程可以在第一个线程之前启动。 这完全取决于线程调度程序。一旦创建了线程,它们就会进入可运行状态,然后由线程调度程序负责执行哪个线程。无法保证哪个线程将首先启动和完成。您可以通过在循环中执行此方法来尝试此行为-

public static void abc() throws InterruptedException {
    final JavaApplication6 h = new JavaApplication6();
    new Thread(){
        public void run(){
            synchronized(this){
              System.out.println("T-10000000000");
            }
        }
    }.start();
    new Thread(){
        public void run(){
            synchronized(this){
              System.out.println("T-2");
            }
        }
    }.start();           
}}

public class JavaApplication61 {
    public static void main(String ar[]) throws InterruptedException{
        for(int i=0; i<100;i++){
            JavaApplication6.abc();
        }
    }

}