Threads and multi-threaded development

Processes and Threads

Before learning thread, we must first understand what is the process. Open your task manager, says the first clear navigation bar process , the point is to go find that many programs you run, which is a process.

like this:

Modern operating systems can execute multiple programs simultaneously, which is multi-tasking. Established on the basis of the process on the thread, such as QQ music this process can be executed simultaneously in play, download, transmission and other activities. This is called multi-threads, each performing different functions.
In the single-core CPU system, you can also run multiple programs at the same time, the program run is preemptive, QQrun 0.001S, chromerun 0.01s, this time people are not aware of it, we will feel while performing. Therefore, in order to improve efficiency, and now mobile phones, computers are very multicore.

The relationship between processes and threads is: a process can contain one or more threads, but at least there will be a thread.

The minimum unit of the operating system task scheduling in fact not process, but the thread.

Process VS thread

Processes and threads that include relationship, but both can be achieved by a multi-tasking multi-process can also be achieved by a thread, can also be mixed multi-process multi-threaded.

And multi-threading compared to multi-process shortcomings are:

  • Create a process to create much larger than the thread overhead, especially on Windows
  • Inter-process communication is slower than the thread, the thread because communication is see to read and write the same variable, fast

Multi-process advantages:

  • Multi-process stability than multi-threaded, multi-process as in the case of the collapse of a process will not affect other processes, any thread crashes cause the entire process to crash.

Create a thread

1. Thread

Example:

public class MyThread extends Thread {  // 线程的主体类
    @Override
    public void run(){  
       System.out.println("Thread is starting");
    }
}

Top MyThreadclass inheritance Thread, override the runmethod. As long as a class inherits such, it means that this class is the main thread of class. run()The main method is thread, multi-thread method to be performed are written in it.
But the run()method can not be called directly, which involves resource scheduling system, you want to start multiple threads, must be start()completed.

The calling thread
public class ThreadDemo {
    public static void main(String[] args) {
     new MyThread().start();
        // 启动新线程
}

java language built-in multi-threading support. When the Java program starts actually started a JVM process. JVM start the main thread to perform the main()method, main()you can start another thread method.

start()Only by Threadcall type instance that represents start a thread.

Results of the
"C:\Program Files\Java\jdk1.8.0_221\bin\java.exe"

Thread is starting

Thus, thread creation success

So it creates a multi-threaded?

Create multi-threaded
// 多线程主体类
public class MyThread extends Thread {
    private String title;
    public MyThread(){
    }
    MyThread(String title){
        this.title = title;
    }
    @Override
    public void run(){
        for (int i = 0; i<10;i++){
            System.out.println(this.title +  "is starting");
            System.out.println(Thread.currentThread().getName());
        }
    }
}



 public static void main(String[] args) {
        new Thread(new MyThread("A"),"线程1").start();
        new Thread(new MyThread("C"),"线程2").start();
        new Thread(new MyThread("B")).start();
    }

Results of the:

This result has several concerns:

  1. Multi-threaded execution is chaotic, uncontrollable
  2. Call is start()a method, but the execution is a run()method

We look at the source code, analyze

public synchronized void start() {
      
        if (threadStatus != 0)  // 判断线程状态
        
        // 每一个线程的类的对象只允许启动一次,重复启动就会抛出这个异常,由run()抛出
            throw new IllegalThreadStateException();
            
        group.add(this);

        boolean started = false;
        try {
        // 调用此方法
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
            
            }
        }
    }

    private native void start0();
   
   // 注释部分被我删掉了,太长了 

We found that start()the method is called start0(), but start0()did not realize, was also nativemodified, so nativeis Shane?

In the process of considering a Java program execution to the developer needs for different levels, support the local operating system function calls. This technique is called JNI(Java Native Interface), but in the Java development process, such use is not recommended. Using this technique, you can use the underlying functions of the operating system, some special handling operation.

When different systems in resource scheduling by its own set of algorithms, in order to call the start()method to start the thread, we must realize start0()that this time JVMwill be different according to the specific implementation of the operating system start0(), everything is summed up everything with cross-platform come.

It also provides, multithreading is only one program, call start Threadclass start()method .

  1. Thread constructor parameter may receive an instance of the object and the name of the thread.

Thread.currentThread().getName() On behalf of the acquiring current thread's name.

In return values ​​also appeared in "Thread-3", which is due Thread is automatically assigned to unnamed thread will not repeat a name.

This is certainly true multi-threaded way to start, but there is a single inherited risk. Below is given another mode.

2. Runnable

First look at each Threadimplementation class

public
class Thread implements Runnable {}

The original Threadis inheritedRunnable

Look again at Runnablethe interface

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

Again surprise, it turned out that the run method is inherited from here.

It is clear, to try it.

// 只需要实现 Runnable,重写run()即可,其他丝毫未变
public class MyThread implements Runnable {
    private String title;
    public MyThread(){
    }
    MyThread(String title){
        this.title = title;
    }
    @Override
    public void run(){
        for (int i = 0; i<10;i++){
            System.out.println(this.title +  "is starting");
            System.out.println(Thread.currentThread().getName());
        }
    }
}




public class ThreadDemo {
    public static void main(String[] args) {
        new Thread(new MyThread("A线程"),"线程1").start();
        new Thread(new MyThread("C线程"),"线程2").start();
        new Thread(new MyThread("B线程")).start();
       // lambda 语法实现
//        new Thread(() -> {
//           System.out.println("启动新的线程");
//       }).start();


    }
}

result:

Perfect matching.

After multi-threaded design and implementation, priority use Runnableinterface.

Not finished, we rely on Runnablewhen the interface implementation, you will find a flaw, that is no return value, and that there is no way to return value to achieve it? Have! Continue to look

3. Callable

In the Java1.5following order to solve the run()problem of method does not return value, introduces a new thread implementation java.util.concurrent.Callableinterface.

We look at Oracle's api documentation:

Callable can be seen when using the definition of a generic, representative of the type of data returned, avoiding the security risks caused downcast

Learn downcast can see another one of my articles: https://www.cnblogs.com/gyyyblog/p/11806601.html

But the problem again, we have said above, multi-threaded, you must use in order to start the Threadclass provides the
start()method call Runnableinterface run()methods, but now Callableand there is no run()way how to do it?

Again find a FutureTaskclass:

public class FutureTask<V>
extends Object
implements RunnableFuture<V>

Construction method:

It may receive a constructor Callabletype parameter

It inherited RunnableFuture<V>, then keep looking up

public interface RunnableFuture<V>
extends Runnable, Future<V>

There was, it appeared, Runnablewe know, there is no return value, and now look Future<V>Gesha

It has a get()way to get a generic return value.

OK, now we can sort out these things about how a relationship found:

Implementation

public class CallableThread implements Callable<String> {  // 继承实现Callable<V>
    // 覆写call()方法
    @Override
    public String call() throws Exception{
        for (int i = 0;i<10;i++){
            System.out.println("*********线程执行、i="+ i);
        }
        return "线程执行完毕";
    }
}



// 调用
        FutureTask<String> task = new FutureTask<>(new CallableThread());
        new Thread(task).start();
        System.out.println("【线程返回数据】" + task.get());

result:

So easy to obtain a return value, or an instance of a core idea of Threadthe object, which may be received by a constructor Rannabletype parameters, call start()start threads.

Summary: Basically, it creates three multi-threaded mode according to the scene to use.

** purely personal understanding, hope to correct the error, common exchange.

Guess you like

Origin www.cnblogs.com/gyyyblog/p/11823842.html