简体   繁体   English

Java:子线程是否锁定了主线程?

[英]Java : Are sub threads lock the main thread?

I am new to Java, I have want to starts 02 thread to increase an attribute of an object and I want to print out the value of this attribute until it reach a certain value.我是Java新手,我想启动02线程来增加一个对象的属性,我想打印出这个属性的值,直到它达到某个值。 I use 02 threads started inside increaseByThread() method.我使用在increaseByThread()方法中启动的 02 个线程。

I use two code snippets as follows but they behave differently.我使用如下两个代码片段,但它们的行为不同。 The first one I use while loop in the main thread to check for the value change but it only print out the last value after two sub-threads finish running and return 40.第一个我在主线程中使用 while 循环来检查值的变化,但它只在两个子线程完成运行并返回 40 后打印出最后一个值。

The second one I use while loop but inside another sub-thread for checking value and it prints out every value, it means that 03 sub-threads are running in parallel (please see the second snippet below)第二个我使用while循环,但在另一个子线程中检查值并打印出每个值,这意味着03个子线程并行运行(请参见下面的第二个片段)

My question is that why in the first snippet, the while loop block only called after test.increaseByThread() finish execution?我的问题是,为什么在第一个片段中,while 循环块仅在test.increaseByThread()完成执行后调用?

public class ThreadIncrease {
    public volatile int[] count={0};
     public void increaseByThread(){
         Runnable first= () -> {
             for(int i=0;i<20;i++) {
                 count[0] = count[0] + 1;
                 try {
                     Thread.sleep(1000);
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
//                 System.out.println(count[0]);
             }

         };

         Runnable second= () -> {
             for(int i=0;i<20;i++) {
                 try {
                     Thread.sleep(1000);
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
                 count[0] = count[0] + 1;
//                 System.out.println(count[0]);
             }

         };
         Thread firstThread=new Thread(first);
         Thread secondThread=new Thread(second);
         firstThread.run();
         secondThread.run();
     }

    public static void main(String[] args) {
        ThreadIncrease test=new ThreadIncrease();
        Runnable check=()->{
            while(true){
                System.out.println(test.count[0]);
                if(test.count[0]<10){
                    System.out.println("count is: "+test.count[0]);
                }
                else{
                    System.out.println("Break");
                    break;
                }
            }
        };
//        Thread checkThread=new Thread(check);
//        checkThread.start();

        test.increaseByThread();
        while(true){
            System.out.println(test.count[0]);
            if(test.count[0]<10){
                System.out.println("count is: "+test.count[0]);
            }
            else{
                System.out.println("Break");
                break;
            }
        }

    }

}

The second one I use while loop but inside another sub-thread for checking value and it prints out every value, it means that 03 sub-threads are running in parallel:第二个我使用while循环,但在另一个子线程中检查值并打印出每个值,这意味着03个子线程并行运行:

    public class ThreadIncrease {
    public volatile int[] count={0};
     public void increaseByThread(){
         Runnable first= () -> {
             for(int i=0;i<20;i++) {
                 count[0] = count[0] + 1;
                 try {
                     Thread.sleep(1000);
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
//                 System.out.println(count[0]);
             }

         };

         Runnable second= () -> {
             for(int i=0;i<20;i++) {
                 try {
                     Thread.sleep(1000);
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
                 count[0] = count[0] + 1;
//                 System.out.println(count[0]);
             }

         };
         Thread firstThread=new Thread(first);
         Thread secondThread=new Thread(second);
         firstThread.run();
         secondThread.run();
     }

    public static void main(String[] args) {
        ThreadIncrease test=new ThreadIncrease();
        Runnable check=()->{
            while(true){
                System.out.println(test.count[0]);
                if(test.count[0]<10){
                    System.out.println("count is: "+test.count[0]);
                }
                else{
                    System.out.println("Break");
                    break;
                }
            }
        };
        Thread checkThread=new Thread(check);
        checkThread.start();

        test.increaseByThread();
//        while(true){
//            System.out.println(test.count[0]);
//            if(test.count[0]<10){
//                System.out.println("count is: "+test.count[0]);
//            }
//            else{
//                System.out.println("Break");
//                break;
//            }
//        }

    }

}

Thread.run() , which you are calling in increaseByThread() runs the Thread's Runnable in the current thread .您在increaseByThread()中调用的Thread.run()在当前线程中运行 Thread 的Runnable I think you have confused it with Thread.start() , which starts a new thread to run the Runnable .我认为您将它与Thread.start()混淆了,后者启动了一个新线程来运行Runnable

See What's the difference between Thread start() and Runnable run() and When would you call java's thread.run() instead of thread.start()?请参阅Thread start() 和 Runnable run() 之间有什么区别以及何时调用 java 的 thread.run() 而不是 thread.start()?

You have not started any new thread yet.你还没有开始任何新的话题。

Each thread needs to run something.每个线程都需要运行一些东西。 That is it's run method.那就是它的运行方法。 But by invoking thread.run you just execute that code on the calling thread, which is your main thread.但是通过调用thread.run ,您只需在调用线程(即您的主线程)上执行该代码。

Instead you need to start the new thread using thread.start() .相反,您需要使用thread.start()启动新线程。 This function will return immediately, and the newly created thread will execute run() in parallel.这个函数会立即返回,新创建的线程会并行执行run()。

Since you were running everything on the main thread the perception is right that the main thread was blocked until all the runs finished.由于您在主线程上运行所有内容,因此在所有运行完成之前主线程被阻塞是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM