The concept of multithreading, how to create and thread state.

The concept of multithreading

Modern operating systems can perform multiple tasks, i.e. they alternate multiple tasks in turn (as our users seem to be doing multiple tasks at the same time).

process

A task in a computer is called a process. Some processes need to perform multiple subtasks to become threads. For example, when we browse the web page, there are not only static text, but also dynamic advertisements on the web page, and so on.

A process can contain one or more threads, but at least one thread. Threads are the smallest unit of tasks scheduled by the operating system, and how they are scheduled depends entirely on the operating system.

The Method of Realizing Multitask

1. Multi-process mode: each process has only one thread;

2. Multithread mode: a process has multiple threads;

3. Multiprocess + Multithreading: High complexity.

Multiprocess and Multithread Comparisons

1. The overhead of creating a process is greater than that of creating a thread.

2. Inter-process communication is slower than inter-thread communication.

3. Multi-process stability is higher than multi-thread stability.

Java Multithreading

A java program is actually a jvm program; the jvm uses a main thread to execute the main method; the main method can start multiple threads.

The characteristics of multithreading are as follows:

Read and write shared data;

Synchronization is often required.

Programming complexity is high and debugging is difficult.

How to create new threads?

Method: Two kinds

1. Create MyThread class, derive from Thread class, override run() method, create MyThread instance, and call start() method.

public class MyThread estends Thread{
    public void run(){
        System.out.println();
    }
}

public class Main{
    public static void main(String[] args){
        Thread t = new MyThread();
        t.start();
    }
}

2. If a class has been derived from a class and cannot be inherited from Thread, implement the Runnable interface, override the run() method, create a Runnable instance in the main() method, create a Thread instance and pass it to the Runnable instance, and call start() with the Thread instance to start the thread.

public class MyThread implements Runnable{
    @Override
    public void run(){
        System.out.printlv("run");
    }
}

public class Main{
    public static void main(String[] args){
        Runnable r = new MyThread();
        Thread t = new Thread(r);
        t.start();
    }
}

Analyse the following code:

public static void main(String[] args) throws InterruptedException {
        System.out.println("main Threads start printing");
        Thread.sleep(1000);
        Thread thread = new Thread(){
            public void run() {
                System.out.println("threa Threads start printing");
                System.out.println("threa Thread End Printing");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();
        System.out.println("main Thread End Printing");
        Thread.sleep(1000);
}

We can only make sure that we print out "main thread starts printing" first. As for the location of "main thread ends printing", we can't know in advance, because how to schedule threads is determined by the operating system. When the start() method is called by thrad, threads outside the main thread are opened. At this point, the two threads begin to run simultaneously.

Attention points

1. Invalid direct call to run() method; 2. New threads must be started by calling start() method

public class Thread implements Runnable{
    public synchronized void start(){
        start0();
    }
}
...
//Implementation of C Code in jvm Virtual Machine
private native void start0();

Main points:

  1. java represents a thread with a Thread object and starts a thread by calling the start() method
  2. A thread object can only call the start() method once
  3. The thread's execution code is the run() method
  4. Thread scheduling is determined by the operating system, but not by the program.
  5. The Threa.sleep() method pauses the current thread for a period of time.

 

Status of threads

Create New, run Runnable (call start() method), blocked Blocked, Waiting, Timed Waiting, Terminated.

Thread termination reason:

  1. Normal termination: execution to return statement in run method
  2. Unexpected termination: termination caused by uncovered exceptions
  3. Not recommended: Call the stop method to force termination of a Thread instance of a thread.

Waiting method: join

class HelloThread extends Thread {
    String name;
    public HelloThread(String name){
        this.name = name;
    }
    @Override
    public void run(){
        System.out.println("Hello:"+name+"!");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class MyThread{
    public static void main(String[] args) throws InterruptedException {
        Thread myThread = new HelloThread("aaa");
        System.out.println("Start printing");
        myThread.start();
        //Waiting for the myThread thread to finish executing
        myThread.join();
        System.out.println("End printing");
    }
}

From the above code, we can find that after "start printing" and "Hello:aaa!", after the printing is finished, we wait for 3 seconds before "end printing" can be output in the console.

That is, the main method waits for the new thread to finish before it continues to execute.

Keywords: Java jvm Programming

Added by Wayniac on Thu, 12 Sep 2019 16:33:34 +0300