Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 调用thread.start()时,首先调用哪个线程_Java_Multithreading - Fatal编程技术网

Java 调用thread.start()时,首先调用哪个线程

Java 调用thread.start()时,首先调用哪个线程,java,multithreading,Java,Multithreading,我的代码是: public class Child extends Thread { public void run(){ synchronized (this) { for(int i=1;i<=5;i++) { System.out.println("child thread");

我的代码是:

    public class Child extends Thread {

        public void run(){
            synchronized (this) 
            {
                for(int i=1;i<=5;i++)
                {   
                    System.out.println("child thread");
                }
            }
        }
    }

class ThreadTest{
    public static void main(String []a) {
        Child child=new Child();
        **child.start();**      
        synchronized (child) 
        {
            for(int i=1;i<=5;i++)
            {   
                System.out.println("parent thread");
            }
        }
    }
}
公共类子线程扩展{
公开募捐{
已同步(此)
{

对于(int i=1;i在
child.start()
调用中的某个地方(即,在start()返回之前),新线程被创建,并且它有资格运行。从那一点开始,看哪个线程将到达它各自的
同步(…)
block first。没有办法知道哪一个会赢,也没有理由认为每次都是同一个赢家


注意:在
线程
对象上同步不是一个好主意。
线程
类也会出于自身的目的在
线程
实例上同步,并且将线程对象用作锁可能会干扰线程类对其的使用

一个好习惯是在私有对象上同步

class MyClass {
    private final Object myLock = new Object();

    SomeType someMethod(...) {
        synchronized(myLock) {
            ....
         }
    }
}

这是因为
synchronized(child)
是在
child\run()中的
synchronized(this)
之前输入的
,偶尔。没有保证。在这种情况下,由调度程序决定是否立即调度新创建的线程。没有保证其他线程会有任何结果,即使是两者的混合。如果要强制执行命令,您需要类似于
倒计时闩锁的东西你的编辑评论太令人失望了。@Tom是我的错,是我的错mistake@SashaSalauyou幸运的是,这不是一次审判;P。