Concurrent artistic context (a) article takes you understand JAVA multithreading

Original technology articles, belongs to the author of all, if reproduced, please indicate the source
public number, to be determined, the former public number of long-term test ash has been frozen

Processes and Threads

We often when it comes to processes and threads, so in the end both what difference does it make?

The so-called 进程, is the operating system for resource allocation and call the smallest unit. For example, we do something, what activities, for this thing, what resources we need, the whole can be understood as a process. And 线程it is the smallest unit CPU scheduling, it depends on the process exists, it is equivalent to the flow of control we take what resources do something.

In the operating system, 进程perform the required load context, mission, saving the context, in order to enhance the efficiency of the operating system into the threads, multiple threads within a process can share the process resources, and we usually refer to multi-threading refers to the 用户线程need distinguish operating system 内核线程.

How the CPU is executed

At present, such as Windows, Linux, MacOs, are time-sharing operating system we use is multi-tasking multi-user.

As for the single-core CPU, the same time can only do one thing, in order to achieve the goal of a multi-user multi-task, use the time slice is the same time period, on a mission. For example, the hostel there are four buddies, but only one computer, we all have to find information online, then the person can only use five minutes, time to let the next person to use their own to the back of continuing to line up.

As for that is orderly, or priority, there are different scheduling algorithms, such as RR(时间片轮转), FCFS(先到先服务), SPN(最短作业优先), SRT(最短剩余时间优先), HRRN(高响应比优先). Other algorithms subsequent columns will further investigate the following example RR algorithm.


RR scheduling, round-robin method (Round-Robin), mainly used for time-sharing operating system.

As mentioned earlier, the basic unit of CPU scheduling is the thread, and the round-robin, is divided into a plurality of time slices, the operating system keeps a ready process FIFO queue, when the CPU is idle, from the head out a ready process, the CPU allocated to the process, this process enjoys the execution of the CPU, to perform tasks of the process within the time slice.

Time slices are typically about 10 ~ 100ms, when the time slice execution is completed, the interrupted current process will be the process into the ready queue tail, the scheduler then CPU assigned to the head of the queue process.

If executed within a time slice, then dispatched the next process.

JAVA thread scheduling

As mentioned above, thread scheduling, in fact, the process of the operating system allocates CPU usage rights, and the main scheduling in two ways, one is 协作式线程调度, one is抢占式线程调度

协作式线程可以控制线程的执行时间,执行完成后,可以告诉操作系统下一个递交的线程,就是可以从一个线程主动切换到另一个线程,但是如果执行的线程出现异常,一直占用CPU资源,则会导致系统阻塞。

抢占式线程的执行,则依赖我们上述的时间片机制,即使出现异常也不会阻塞系统
复制代码

java is to use preemptive thread scheduling, if you want a long time point thread of execution can set the thread level, but does not fly. The cooperative thread LUA in 协同例程the reflected, java also has Quasar can support, if accustomed to asynchronous programming, and high performance requirements, consider a try.

JAVA thread state

(Handmade) directly FIG.

The figure illustrates the operation between states and the state of the thread switching, the main five states as follows,

  1. New (New), this time the thread has been created, but does not start
  2. Run (Runable), this status include Running and Ready, the thread starts, is Ready status, front mentioned CPU assignment, when a thread with executive powers CPU, then becomes the Running state, the thread yield if run, then let the implementation of the right to re-become ready
  3. Waiting (Waiting), points wait indefinitely and there is a deadline wait, wait (), join (), park (), needs to be displayed wake up other threads, if not wake up it will have to wait until the process is terminated
  4. Blocked (Blocked), strictly speaking, obstruction and wait there are some differences, waiting will cause the current thread is blocked, and if a synchronous call, you need to be woken up before they can continue. The blocking also contain other obstruction, such as in obtaining an exclusive lock if other threads have access to resources locked, the current thread is blocked waiting for him to release the lock
  5. End (Terminalted), the thread has ended

JAVA thread use

JAVA with a threaded There are three main ways

Thread

# 继承Thread
static class ThreadTest extends Thread{
    
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + ", Thread example.....");
    }
}
复制代码

Runnable

# 实现Runnable接口,实现run()
static class RunnableTest implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + ", Runnable example.....");
    }
}
复制代码

Callable If we need to return a value, use Callable

# 实现Callable接口,实现call(),并返回相应的值
static class CallableTest implements Callable<String> {

    @Override
    public String call() throws Exception {
        System.out.println(Thread.currentThread().getName() + ", Callable example.....");
        return "call result";
    }
}
复制代码

test

public static void main(String[] args) throws ExecutionException, InterruptedException {
    ThreadTest threadTest = new ThreadTest();
    threadTest.start();

    Thread runnableTest = new Thread(new RunnableTest());
    runnableTest.start();

    FutureTask<String> futureTask = new FutureTask<String>(new CallableTest());
    Thread callableTest = new Thread(futureTask);
    callableTest.start();
    
    String result = futureTask.get();
    System.out.println("callable result :" + result);
}
复制代码

result

Thread-0, Thread example.....
Thread-1, Runnable example.....
Thread-2, Callable example.....
callable result :call result
复制代码

The benefits of concurrent programming

Directly on the example, immediately double eleven, and adding warehouse a pile of goods, there is only one person to move (A), tentatively have one million, if A only once to move one, then a total of handling one million times, if we can join a b conveyed and a together, assuming the two conveying time the same, then the two respective transfer 500,000 times, can get.

Move cargo

static class Carry extends Thread{

    /** 搬运人*/
    private String peopleName;
    /** 搬运次数*/
    private int carryNum;

    public Carry(String peopleName) {
        this.peopleName = peopleName;
    }

    @Override
    public void run() {
        while (!isInterrupted()) {
            synchronized (cargoNum) {
                if (cargoNum.get() > 0) {
                    cargoNum.addAndGet(-1);
                    carryNum++;
                } else {
                    System.out.println("搬运完成,员工:" + peopleName + ",搬运:[" + carryNum + "]次");
                    interrupt();
                }
            }
        }
    }
}
复制代码

A separate transfer

/** 货物个数*/
static AtomicInteger cargoNum = new AtomicInteger(1000000);

public static void main(String[] args) {
    Carry carry1 = new Carry("甲");

    carry1.start();
}

# 结果
搬运完成,员工:甲,搬运:[1000000]次
复制代码

A and B move together

/** 货物个数*/
static AtomicInteger cargoNum = new AtomicInteger(1000000);

public static void main(String[] args) {
    Carry carry1 = new Carry("甲");
    Carry carry2 = new Carry("乙");

    carry1.start();
    carry2.start();
}

# 结果
搬运完成,员工:乙,搬运:[272708]次
搬运完成,员工:甲,搬运:[727292]次
复制代码

Above we simulate the case of two moving goods, during transportation with A and B both can work in parallel, more efficient, if coupled with C, D .... will be faster.

Now the CPU generally supports Hyper-Threading technology, namely a physical endorsed as two logical cores, and single-CPU are basically multi-core, ranging from a few cores, as many as several hundred, if we're alone just to make a work, then the other will be in an idle state, for example, I now have ten workers can move goods, but I just let the armor go, then other labor costs equivalent wasted.

Therefore, the most immediate benefit of concurrent programming is the rational use of machine resources, improve processing efficiency. Especially in asynchronous programming, fully press the CPU performance.

Examples of uses synchronizedand AtomicInteger, in order to ensure that the total amount of the remaining goods in multiplayer handling, the value is right, you can try to AtomicIntegerreplace Integeror remove synchronized, the two eventually a total of handling and will not be consistent with the total amount of the original goods.

So many people, things are much, concurrent programming, we need to consider the FAQ thread safety, context switching, etc. These will be presented in the following sections.

Guess you like

Origin juejin.im/post/5db9a2225188253cef5554c5