Five minutes to take you a detailed understanding of multi-threaded Java

Multithreading

  • In the traditional operating system, the program can not be run independently as a stand-alone resource allocation and the basic unit is a process. In the OS is not configured
  • System, the implementation of the program execution order, i.e., in a program to be executed, before allowing another program execution; in multiprogramming environment allows multiple programs concurrently. Between these two implementation program has significantly different. This feature is also complicated by the program when the execution was a result of the introduction of the concept of the process in Caozuojitong in.
  • Since the 1960s, people put forward the concept of the process, the OS has been able to process as the basic unit has the resources and independence running. Until the mid-1980s, people made less progress than the basic unit can operate independently - threads (Thread), trying to use it to improve the degree of concurrent execution of programs within the system, which can further improve the system throughput . Especially after entering the 1990s, the rapid development of multiprocessor systems, threads can better improve the level of implementation of the program than the parallel process, give full play to the advantages of multiprocessor, which in recent years has launched a OS multiprocessor also have introduced threads to improve the performance of the OS.
  • ---------------- above is taken from "Computer Caozuojitong - Tang Xiaodan, eds version 3"

The concept of process

  • It is running programs. That is, representing the memory area occupied by the program lock.

Feature

  • Independence: The process is system independent entities exist, it can have its own independent resources, each process has its own private address space. In the case of the process itself has not been allowed, a user can not directly access the process address space of another process.

  • Dynamics: the difference between the process and procedures that the program is just a static set of instructions, and the instruction process is an ongoing activity in the system collection. In the process of adding the concept of time, the process has its own life cycle and various states, these concepts in the program are not available.

  • Concurrency: multiple processes can execute concurrently on a single processor, multiple processes do not affect each other.


The concept of threads

  • Thread (thread) is a minimum unit capable of operating the system operation schedule. It is included in the process, the actual operation of the unit process. A process can open multiple threads.

  • It extends the concept of multi-threaded multi-process, so that the same process can handle multiple concurrent tasks.

  • In short, after a program running at least one process, a process contains multiple threads.

  • If a process has only one thread, this program is known as single-threaded.

  • If a process in a number of execution paths are called multi-threaded programs.
    Here Insert Picture Description


The relationship between process and thread
Here Insert Picture Description
from the image above you can see that an operating system can have multiple processes, a process can have multiple threads, each process has its own memory, each thread in a process of shared memory, each thread has its own separate memory. (Remember clearly this relationship is very important!) So I want to use multithreading technology, we must first have a process, the process of creating the OS is created, you can achieve it? No, usually c or c ++ language completed.

Characteristics multithreading

  • Randomness
    Here Insert Picture Description
    thread state
    Here Insert Picture Description
    thread life cycle, a total of five states:

  • 1) a new state (New): After the object created when a thread that enters the new status, such as: Thread t = new MyThread ();

  • 2) the ready state (Runnable): When the start () method (t.start (the calling thread object);), the thread that is ready state. Thread in the ready state, is illustrative of this thread is ready, waiting for the CPU scheduled for execution at any time, not to say that the implementation of the t.start () This thread will be executed immediately;

  • 3) run state (Running): When the CPU thread scheduling is started in a ready state, and this time was able to really execute threads that go into run mode. Note: ready state is the only means of access to the operating state, that is, the thread execution in order to enter the running state, first of all must be in a state of readiness;

  • 4) blocking state (Blocked): running the thread for some reason, temporarily give up the right to use the CPU, stop the execution, this time into the block until it enters the ready state, have a chance to be called again CPU to proceed to the operating state;

  • 5) arising for various reasons blocked, the blocked state can be divided into three types:

  • a) Wait blocking: a thread of execution running state wait () method, so that the thread enters the wait state obstruction;
  • b) synchronous blocking: get synchronized thread synchronization lock failure (because the lock was occupied by another thread), it will enter synchronous blocking state;
  • c) the blocked: The sleep () or join the calling thread () or issue the I / O request, the thread will enter into blocking state. When sleep () timeout, the Join () or a timeout wait for a thread to terminate, or I / O processing is completed, the thread into the ready state again.
  • 6) death state (Dead): thread execution is over or due to abnormal exit the run () method, the thread end of the life cycle.

Multithreading create 1: Inheritance Thread

Essentially Thread class is to achieve an instance of Runnable interface, representing an instance of a thread. The only way to start the thread is () instance method by start Thread class. Start () method is a native method, it will notify the underlying operating system, and ultimately by the operating system to start a new thread, the operating system executes run () method. This is very simple way to achieve multi-threaded, through their classes directly extend Thread, and replication run () method, you can start a new thread and execute the run () method define yourself. (Simulated open multiple threads, each thread calls the run () method.)

Common method

String getName()

      返回该线程的名称。 

static Thread currentThread()

      返回对当前正在执行的线程对象的引用。 

void setName(String name)

      改变线程名称,使之与参数 name 相同。

static void sleep(long millis)

 在指定的毫秒数内让当前正在执行的线程休眠(暂停执行),此操作受到系统计时器和调度程序精度和准确性的影响。

void start()

      使该线程开始执行;Java 虚拟机调用该线程的 run 方法。

Thread(String name)

      分配新的 Thread 对象。

test

public class Test1  {
    public static void main(String[] args) {
       //3、创建线程对象
       ThreadDemo t1 = new ThreadDemo("钢铁侠");
       ThreadDemo t2 = new ThreadDemo("美队");
       //4、开启线程:谁抢到资源谁就先执行
       t1.start();
       t2.start();
       //t1.run();//当做常规方法调用,且 不会发生多线程现象
    }
}

//1、作为Thread的子类,并重写run方法。把多线程的业务写在run方法中
class ThreadDemo extends Thread{  
public ThreadDemo() {}
    public ThreadDemo(String name) {
       super(name);
    } 
    @Override
    public void run() {
       //2、默认实现是super.run();
       for (int i = 0; i < 10; i++) {
           System.out.println(getName()+i);
       }
    }
}

Multithreading create 2: implement Runnable

If your class already extends another class, multiple inheritance can not, at this time, you can achieve a Runnable interface.

Common method

void run()

      使用实现接口 Runnable 的对象创建一个线程时,启动该线程将导致在独立执行的线程中调用对象的 run 方法。 

test

public class Test2 {
    public static void main(String[] args) {
       MyThread t = new MyThread ();
       //2,构造创建对象,传入Runnable子类
       Thread target = new Thread(t); 
	   Thread target2 = new Thread(t);
       //开启线程
       target.start();
       target2.start();
    }
}

//1,实现Runnable接口,重写run()
class MyThread implements Runnable{
    @Override
    public void run() {
       for (int i = 0; i < 10; i++) {
       System.out.println(Thread.currentThread().getName()+" "+i);
       }
    }
}

Note : You can see the execution order is chaos, we already know the start () method simply inform the operating system thread is ready, what specific time to perform, the operating system to decide, we have no control over the JVM. This is why out of order, it is normal.


Compare
Here Insert Picture Description

Genlock: synchronized

There may be problems in the code package together, only once let a thread. Synchronized via sychronized keyword. When operating multiple objects share data synchronization lock can be used to solve thread safety issues.

synchronized (object) {
requires synchronization code;
}

Features
1, Premise 1, two or more thread synchronization needs.
2, premise 2, between multiple threads must use the same lock.
3, the disadvantage is that synchronization can reduce the performance of programs, in order to ensure thread safety, have to sacrifice performance.
4, may be modified method is called a synchronization method, the lock object using this.
5, may be modified code blocks referred to as sync block, can be any lock object.


Published 36 original articles · won praise 13 · views 1058

Guess you like

Origin blog.csdn.net/weixin_44598691/article/details/104870494