【问题标题】:Thread order using synchronized使用同步的线程顺序
【发布时间】:2017-05-02 09:48:04
【问题描述】:

有没有输出不是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();           
}}    

【问题讨论】:

标签: java multithreading thread-safety synchronized


【解决方案1】:

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

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

此外:由于线程之间的切换(由上述线程调度程序进行),first 可以先开始,但最后完成。

即使您多次运行此应用并“证明”该顺序相同,也不能保证此顺序在下一次运行时不会改变。

【讨论】:

    【解决方案2】:

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

    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();
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 2019-11-05
      相关资源
      最近更新 更多