Two Traditional Ways to Realize Multithreading

Keywords: Java jvm

The first is to create a class that inherits the Thread class and override the run method of the Thread class. The code is as follows:

class Thread1 extends Thread {
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);// Thread Sleep 1 s
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());// Print the current thread name
        }
    }
}

public class Test {

    public static void main(String[] args) {

        Thread1 thread1 = new Thread1();
        thread1.start();//Startup thread
    }

}

 

The second way is to create a class to implement the Runable interface, rewrite the run method of the Runable interface, and pass the object of this class as a parameter to the parametric construction method of the Thread class. The code is as follows:

class Thread2 implements Runnable{

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);// Thread Sleep 1 s
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());// Print the current thread name
        
    }}
}

public class Test {

    public static void main(String[] args) {

        Thread thread = new Thread(new Thread2());
        thread.start();//Startup thread
    }
}

 

The difference between the two approaches is that if a class inherits Thread, it is not suitable for resource sharing. But if the Runable interface is implemented, resource sharing can be easily achieved.

Implementing the Runnable interface has advantages over inheriting the Thread class:

1: For multiple threads with the same program code to process the same resource

2): You can avoid the limitation of single inheritance in java

3: Increase the robustness of the program, code can be shared by multiple threads, code and data independence

Note: The main method is actually a thread. In java, all threads are started at the same time. When and which thread is executed first depends entirely on who gets CPU resources first.

In java, at least two threads are started each time the program runs. One is the main thread and the other is the garbage collection thread. Because whenever a class is executed using a Java command, a jvm is actually started, and each jvm actually starts a process in the operating system.

Posted by arth on Thu, 31 Jan 2019 17:15:16 -0800