Java multi-threading and Implementation Overview

1. processes and threads

1.1 defined processes and threads

  • Process : execution cycle of a program;

  • Thread : a program to perform multiple tasks, each task is called a thread;

  • Difference between the two

  1. Cost: Process : When you open an application, such as opening multiple IDEA, every time you open will need to consume memory and time consuming; Thread : open an application, the thread is consuming resources in this process , so less overhead;
  2. Data sharing: the thread is created in a process, so data can be shared between threads, communication is more convenient and effective; the need to communicate between processes via TCP protocol network;
  • Multi-threaded applications: such as opening a browser, you can while downloading something, browse the Web;
  • High concurrency (multiple threads): There are a large number of users accessing the system;
  • Problems caused by high concurrency: server memory is not enough, the program competition for resources, can not handle new requests.

1.2 thread state

Here Insert Picture Description
(1) When a thread is created, will not be executed immediately, because it wants to get the CPU time slice, which relies on the operating system scheduling system;
(2) For example: When you create a thread, first enter the ready state , if the CPU time slice 1 delicate, this time the thread is not executed, by running state to the ready state continues to wait for the system operator;
(3) when the system is the lack of a resource, such as the presence of input and output, by the thread running state to the blocked state , unblocking become ready, waiting for CPU allocation of time slices.

2. Java multi-threaded implementation

2.1 direct successor Thread class started threads

java.lang.Thread core class is a thread operation. Create a new thread easiest way is the direct successor Thread class, and then override the run () method in this class.

public class MyThread extends Thread{

    private String message;
    public MyThread(String message){
        this.message = message;
    }

    @Override
    public void run() {					//覆写Thread中的run()方法
        System.out.println(message);
    }

    public static void main(String[] args) {
        MyThread myThreadA = new MyThread("线程A");
        MyThread myThreadB = new MyThread("线程B");
        MyThread myThreadC = new MyThread("线程C");

        myThreadA.start();				//调用run()方法
        myThreadB.start();
        myThreadC.start();
    }

}
/*
线程A
线程C
线程B
*/

== Why to call the run () method start () method, rather than run () direct implementation? ==
by looking at the start source code analysis:
Here Insert Picture Description

  1. start () method was called first START0 () method, and this method is only a statement of the method is not implemented, and uses the native keyword defined; refers to a native calls the native function of the native system.
	private native void start0();
  1. Thread class has registerNatives native method, the main role is to register a number of methods for local use Thread, such as start0 (), stop () and the like. This static method on a statement block, when the class is loaded into the JVM when it is invoked, and then register the corresponding native methods.
    So Java thread calls the run () method actually calls JVM_StartThread method .
  2. Thus, by the above, we can see Java thread creation process is as follows:
    Here Insert Picture Description

2.2 Runnable () interface multithreading

Runnable interface has an abstract method run (), run Thread class () method is implemented Runnable interface. Thread class constructor can provide acceptable Runnable interface object.
Here Insert Picture Description
Example: Use methods to achieve multi-threaded Runnable

public class MyRunnable implements Runnable{
    @Override
    public void run() {
        System.out.println("自定义的Runnable接口实现类:"+LocalDateTime.now());
    }

    public static void main(String[] args) {
        Runnable runnable = new MyRunnable();
        Thread threadA = new Thread(runnable);
        threadA.start();

        Thread threadB = new Thread(runnable);
        threadB.start();
    }
}
/**
自定义的Runnable接口实现类:2019-03-25T22:31:15.476
自定义的Runnable接口实现类:2019-03-25T22:31:15.476
*/

Typically, Runnable interface objects may be used for anonymous inner classes or Lambda expression defined .
Example: Use anonymous inner classes and Lambda expressions defined

public class MyRunnable implements Runnable{
    @Override
    public void run() {
        System.out.println("自定义的Runnable接口实现类:"+LocalDateTime.now());
    }

    public static void main(String[] args) {
    Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Thread1");
            }
        });
        thread1.start();

        Thread thread2 = new Thread(()-> System.out.println("Thread2"));
        thread2.start();
    }
}
/**
Thread1
Thread2
*/

2.3 Thread and Runnable difference

  1. Use the Thread class: only single inheritance
  2. Use Runnable, can solve a single inherited defect, because Runnable is an interface, so you can share data

Example: Thread implemented using a ticket

public class MyTickThread extends Thread {

    private int tick = 10;

    @Override
    public void run() {
        while (this.tick > 0){
            this.tick--;
            System.out.println("剩余票数:"+this.tick);
        }
    }

    public static void main(String[] args) {
        /*
         * 每实例化一个对象,调用本类方法都是独立的,不能实现数据共享
         */
        new MyTickThread().start();
        new MyTickThread().start();
        new MyTickThread().start();
    }
}

Example: Using the example implemented Runnable buying

public class MyTickRunnable implements Runnable{
    private int tick = 10;

    @Override
    public synchronized void run() {
        while(this.tick > 0){
            this.tick--;
            System.out.println("剩余票的数量:"+this.tick);
        }
    }

    /**
     * 因为target是Runnable类型,每次访问的是同一个类中的方法,实现数据共享
     */
    public static void main(String[] args) {
        Runnable target = new MyTickRunnable();
        new Thread(target).start();
        new Thread(target).start();
        new Thread(target).start();

    }
}

Guess you like

Origin blog.csdn.net/mi_zhi_lu/article/details/88784902