Detailed explanation of Java multithreading (2) ------ how to create processes and threads

Detailed explanation of Java multithreading (1) ------ Introduction of the concept: https://blog.csdn.net/weixin_39816740/article/details/80089790

 

  In the previous blog, we have introduced the difference between concurrency and parallelism, as well as the understanding of processes and threads, so how to create processes and threads in Java?

 

1. Create a process in the Windows operating system

  In the windows operating system, we usually create a process to open an application software, which creates a process in the computer. More primitively, we do it in the command prompt (we use the process of opening Notepad as an example):

  The first step: windows+R, enter cmd, open the cmd command prompt

      

  Step 2: Enter notepad in the command prompt, press Enter and the Notepad application will pop up

      

 

 PS: Common Windows application software commands

    1. regedit : Open the Registry Editor

    2. control : open the control panel

    3. msconfig : open system configuration

    4. gpedit.msc : open local group policy

    5. explorer : open the resource manager

    6, taskmgr : task manager

    7. logoff : log off the computer directly

    8. osk : open the on-screen keyboard

    9. calc : open the calculator

    10. mspaint: call up the drawing software

    11. dxdiag : View the detailed configuration information of the computer

    12. mstsc: open a remote desktop connection

    13. systeminfo : View basic computer information

    14, notepad: Open Notepad

      

 

2. Create a process in Java

 

The first method: create a process through the exec() method of the Runtime class

1
2
3
4
5
public class Runtime
extends Object
①、表示当前进程所在的虚拟机实例,每个Java应用程序都有一个Runtime类的Runtime ,允许应用程序与运行应用程序的环境进行接口。
②、由于任何进程只会运行与一个虚拟机实例当中,即只会产生一个虚拟机实例(底层源码采用 单例模式)
③、当前运行时可以从getRuntime方法获得。

   

 

  As can be seen from the above source code, the constructor is privatized, that is, we cannot create a new Runtime instance externally, but internally it gives us a method getRuntime() to obtain the Runtime instance.

 

Create a Notepad process through the Runtime class

1
2
3
4
5
6
7
8
9
public class ProcessTest {
     
     public static void main(String[] args) throws Exception {
         Runtime run = Runtime.getRuntime();
         //打开记事本
         run.exec( "notepad" );
     }
 
}

  

  

The second method: create a thread through ProcessBuilder

1
2
3
public final class ProcessBuilder
extends Object<br>①、此类用于创建操作系统进程。
②、每个ProcessBuilder实例管理进程属性的集合。 start()方法使用这些属性创建一个新的Process实例。 start()方法可以从同一实例重复调用,以创建具有相同或相关属性的新子进程。

1
2
3
4
5
6
7
8
9
public class ProcessTest {
     
     public static void main(String[] args) throws Exception {
         //打开记事本
         ProcessBuilder pBuilder = new ProcessBuilder( "notepad" );
         pBuilder.start();
     }
 
}

  

 

  

3. Create a thread in Java

The first method: inherit the Thread class

1
2
3
public class Thread
extends Object
implements Runnable  

 

Steps: 1. Define a thread class A that inherits from the java.lang.Thread class

   2. Override the run() method of the Thread class in class A

   3. Write the operations that need to be performed in the run() method

   4. In the main method (thread), create a thread object and start the thread

      Create a thread class: A class a = new A() class;

      Call the start() method to start the thread: a.start();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.ys.thread;
 
class Thread1 extends Thread{
     @Override
     public void run() {
         for ( int i = 0 ; i < 10 ;i++){
             System.out.println( "播放音乐" +i);
         }
     }
}
 
public class ThreadTest {
     public static void main(String[] args) {
         for ( int i = 0 ; i < 10 ; i++){
             System.out.println( "玩游戏" +i);
             if (i== 5 ){
                 Thread1 th1 = new Thread1();
                 th1.start();
             }
         }
     }
 
}

  result:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
玩游戏 0
玩游戏 1
玩游戏 2
玩游戏 3
玩游戏 4
玩游戏 5
玩游戏 6
玩游戏 7
玩游戏 8
玩游戏 9
播放音乐 0
播放音乐 1
播放音乐 2
播放音乐 3
播放音乐 4
播放音乐 5
播放音乐 6
播放音乐 7
播放音乐 8
播放音乐 9

  Note: When we look at the results, it is not that there are 5 players who play games first and then play music. This is the result of thread scheduling. Two threads are competing for CPU resources at the same time, that is, the final result. The first 5 games are inevitable. It appears first, and when the music is played later depends on how the CPU is scheduled, which is random. We cannot interfere.

 

 

The second method: implement the Runnable interface

1
2
@FunctionalInterface
public interface Runnable

  

1. The Runnable interface should be implemented by any class whose instance will be executed by a thread. The class must define a parameterless method called run.
2. This interface is designed to provide a common protocol for objects that wish to execute code when active. This class has only one run() abstract method in its entirety

 

步骤:1、定义一个线程类 A 实现于 java.lang.Runnable 接口(注意:A类不是线程类,没有 start()方法,不能直接 new A 的实例启动线程)

   2、在 A 类中覆盖 Runnable 接口的 run() 方法

   3、在 run() 方法中编写需要执行的操作

   4、在 main 方法(线程)中,创建线程对象,并启动线程

      创建线程类:Thread t = new Thread( new A类() ) ;

      调用 start() 方法启动线程:t.start();

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Runnable1 implements Runnable{
     @Override
     public void run() {
         for ( int i = 0 ; i < 10 ;i++){
             System.out.println( "播放音乐" +i);
         }
     }
}
 
public class RunnableTest {
     public static void main(String[] args) {
         for ( int i = 0 ; i < 10 ; i++){
             System.out.println( "玩游戏" +i);
             if (i== 5 ){
                 Thread th1 = new Thread( new Runnable1());
                 th1.start();
             }
         }
     }
 
}

  

 

 第三种方法:使用匿名内部类创建线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static void main(String[] args) {
         for ( int i = 0 ; i < 10 ; i++){
             System.out.println( "玩游戏" +i);
             if (i== 5 ){
                 new Thread( new Runnable() {
                     @Override
                     public void run() {
                         for ( int i = 0 ; i < 10 ;i++){
                             System.out.println( "播放音乐" +i);
                         }
                     }
                 }).start();
             }
         }
     }

  

 

注意:

1、启动线程是调用 start() 方法,而不是 调用 run() 方法。

  解析:run()方法:在本线程内调用run()方法,和其他方法没有什么区别,可以重复多次调用;

     start()方法:启动一个线程,实际上还是调用该Runnable对象的run()方法。

     打开 Thread 类的源码,start()方法里面有一句:

        private native void start0();  //native 关键字:本地程序调用    

    native关键字指的是Java本地接口调用,即是使用Java调用本地操作系统的函数功能完成一些特殊的操作,而这样的代码开发在Java中几乎很少出现,因为Java的最大特点是可移植性,如果一个程序 只能在固定的操作系统上使用,那么可移植性就将彻底丧失,多线程的实现一定需要操作系统的支持,那么start0()方法实际上就和抽象方法很类似,没有方法体,而是交给JVM 去实现,即在windows下的JVM可能使用A方法实现start0(),在linux下的JVM可能使用B方法实现start0(),在调用时并不会关心具体是何方式实现了start0()方法,只会关心最终的操作结果,交给 JVM去匹配了不同的操作系统。

 

2、不能多次启动同一个线程,即多次调用 start() 方法,只能调用一次,否则报错:

  

 

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325580222&siteId=291194637