Concurrent Programming Getting Started

1, the difference between threads and processes

Process is the set of all threads, each thread is a path of execution process.

For example: by looking at the list of windows Task Manager, we can run the exe file in memory understood as a process, the process is the basic unit run by the operating system management.

2. Why use multithreading?

Mainly to improve efficiency in a multithreaded program, but need to pay attention not to use multi-threading will be able to improve performance, but some cases can degrade performance.

Multi-threaded application scenarios:

2.1, to avoid clogging

We know that in our single-threaded, the code is executed sequentially, if a blockage has occurred in front of the operation, it will affect the operation of the back, and this time can use multiple threads, can be understood as an asynchronous call; in fact, the front end of ajax is a good example, is turned on by default ajax asynchronous, when calling the browser will start a new thread without blocking the normal operation of the current page;

2.2, to avoid idle CPU

Http server to an example, if only a single thread in response to HTTP requests, a request that is processed, then the process a request, then, CPU execution there is a lot of idle time;

Because processing a request, often related to the RPC, database access, disk IO and other operations, the speed of these operations than many CPU slow, and while waiting for the response, CPU but not to deal with a new request, so the http server performance on poor;

So many web container, are used to create a new thread for each request in response to the ways, so that the waiting time to wait for IO operations of A's request, we can continue to process requests B, responsiveness to concurrent like a lot .

3, multi-threaded two common ways to create

3.1, inheritance Thread class, override the run method
/**
 * author:  niceyoo
 * blog:    https://cnblogs.com/niceyoo
 * desc:
 */
public class ThreadDemo {
    public static void main(String[] args) {
        System.out.println("-----多线程创建开始-----");
        /* 1.创建一个线程*/
        CreateThread createThread = new CreateThread();
        /* 2.开始执行线程 注意 开启线程不是调用run方法,而是start方法*/
        System.out.println("-----多线程创建启动-----");
        createThread.start();
        System.out.println("-----多线程创建结束-----");
    }
}

class CreateThread extends Thread {

    /*run方法中编写 多线程需要执行的代码*/
    @Override
    public void run() {
        for (int i = 0; i< 10; i++) {
            System.out.println("i:" + i);
        }
    }
}

Print Results:

-----多线程创建开始-----
-----多线程创建启动-----
-----多线程创建结束-----
i:0
i:1
i:2
i:3
i:4
i:5
i:6
i:7
i:8
i:9

After thread calls start () method, the code is not executed from top to bottom, but there is a new executive branch.

Note: Paint demonstration multithreading different execution paths.

3.2, to achieve Runnable interface, override the run method
/**
 * author:  niceyoo
 * blog:    https://cnblogs.com/niceyoo
 * desc:
 */
class CreateRunnable implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i< 10; i++) {
            System.out.println("i:" + i);
        }
    }
}

public class ThreadDemo2 {
    public static void main(String[] args) {
        System.out.println("-----多线程创建开始-----");
        /* 1.创建一个线程 */
        CreateRunnable createThread = new CreateRunnable();
        /* 2.开始执行线程 注意 开启线程不是调用run方法,而是start方法 */
        System.out.println("-----多线程创建启动-----");
        Thread thread = new Thread(createThread);
        thread.start();
        System.out.println("-----多线程创建结束-----");
    }
}

Print Results:

-----多线程创建开始-----
-----多线程创建启动-----
-----多线程创建结束-----
i:0
i:1
i:2
i:3
i:4
i:5
i:6
i:7
i:8
i:9
Using inheritance Thread class or Runnable interface that implement good?

Well that implement Runnable interface, scalability inheritance is not strong, java total only supports single inheritance, if a class inheritance Thread class can not inherit the other.

4, daemon thread

java There are two threads, one is user threads, one is the guardian of the thread.

  • User threads: threads from custom created, the main thread to stop, will not stop user threads.

  • Daemon threads: the current process does not exist or stop the main thread, the daemon will be stopped.

How to use the daemon thread?

Just call setDaemon (true) method to set a daemon thread.

/**
 * author:  niceyoo
 * blog:    https://cnblogs.com/niceyoo
 * desc:
 */
public class DaemonThread {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                    }
                    System.out.println("我是子线程...");
                }
            }
        });
        thread.setDaemon(true);
        thread.start();
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(100);
            } catch (Exception e) {

            }
            System.out.println("我是主线程");
        }
        System.out.println("主线程执行完毕!");
    }
}

operation result:

...
我是主线程
我是子线程...
我是主线程
主线程执行完毕!

See results from running, main function is executed over, followed daemon thread stopped.

5, multi-threaded operating status

Create a thread from running to the end, always in one of five states the following:

New state, ready state, running state, blocking state and a state of death.

5.1, the new state

When a thread is created with the new operator, new Thread® e.g., the thread has not started to run, in this case a new thread state. When a thread is in the nascent state, the program code that has not yet started running thread

5.2, ready state

A new thread is created does not start automatically, to execute the thread, the thread must call the start () method. When calling thread object start () method to start a thread that is, create a system resource threads running start () method, and schedule threads run run () method. After the start () method returns, the thread is in the ready state.

Thread a state of readiness does not necessarily run immediately run () method, the thread must also compete with other thread CPU time, CPU time before they can obtain only running thread. Because a single CPU in a computer system, it is impossible to run multiple threads simultaneously, one time only one thread is running. Therefore, at this time there may be multiple threads in the ready state. The system of multiple threads in the ready state is run by the Java thread scheduler (thread scheduler) to schedule.

5.3, the operating state

When the thread gets CPU time, before it went into operation, really started run () method.

5.4, ​​blocked state

Thread running process, it may be due to various reasons into the blocked state:

  1. Thread to sleep by calling sleep method;
  2. A thread calls blocked on I / O operation, i.e. the operation is completed before entering the output operation does not return to its caller;
  3. Thread trying to get a lock, but the lock is being held by another thread;
  4. Thread is waiting for a trigger condition;
5.5, the state of death

There are two reasons why the thread death:

  1. run method exits normally and natural death,
  2. An uncaught exception terminates the thread run method sudden death.

In order to determine whether the current thread alive (that is, either can be run either be blocked), use isAlive () method. If you are running or blocked, it returns true; if the thread is still new and not run the state, or the death of a thread, false is returned.

Action 6, join () method

Multithreading is also a priority of the execution of the so-called priority, whether the cpu is particularly concerned about the little brother, the higher the priority, the more natural the benefits obtained.

When performing the younger brother .join () method in which the main thread, the main thread should be considered the implementation of the right to give younger brother.

for instance:

After you create a thread, how to get the child thread is finished, the main thread to perform it?

public class ThreadDemo3 {

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep(10);
                    } catch (Exception e) {

                    }
                    System.out.println(Thread.currentThread().getName() + "i:" + i);
                }
            }
        });
        t1.start();
        /* 当在主线程当中执行到t1.join()方法时,就认为主线程应该把执行权让给t1 */
        t1.join();
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(10);
            } catch (Exception e) {

            }
            System.out.println("main" + "i:" + i);
        }
    }
}

Print Results:

Thread-0i:0
Thread-0i:1
Thread-0i:2
Thread-0i:3
Thread-0i:4
Thread-0i:5
Thread-0i:6
Thread-0i:7
Thread-0i:8
Thread-0i:9
maini:0
maini:1
maini:2
maini:3
maini:4
maini:5
maini:6
maini:7
maini:8
maini:9

7, priority

While the top priority mentioned in the introduction join method, but after using the join () method, the thread has become a completely dominant, it probably is not what you want.

The basic form of a modern operating system is scheduled to run division of the thread, the thread assigned time slice of the resulting number determines how many threads to use processor resources, also corresponds to the thread priority concept. In the JAVA thread, int priority through a control precedence, range from 1 to 10, wherein the maximum 10, the default value is 5. The following are some of the source code on the amount and priority of methods (based on 1.8).

class PrioritytThread implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().toString() + "---i:" + i);
        }
    }
}

public class ThreadDemo4 {
    public static void main(String[] args) {
        PrioritytThread prioritytThread = new PrioritytThread();
        Thread t1 = new Thread(prioritytThread);
        Thread t2 = new Thread(prioritytThread);
        t1.start();
        /* 注意设置了优先级, 不代表每次都一定会被执行。 只是CPU调度会有限分配 */
        t1.setPriority(10);
        t2.start();
    }
}

Print Results:

Thread[t1,10,main]---i:0
Thread[t1,10,main]---i:1
Thread[t1,10,main]---i:2
Thread[t1,10,main]---i:3
Thread[t1,10,main]---i:4
Thread[t1,10,main]---i:5
Thread[t1,10,main]---i:6
Thread[t1,10,main]---i:7
Thread[t1,10,main]---i:8
Thread[t1,10,main]---i:9
Thread[t2,5,main]---i:0
Thread[t2,5,main]---i:1
Thread[t2,5,main]---i:2
Thread[t2,5,main]---i:3
Thread[t2,5,main]---i:4
Thread[t2,5,main]---i:5
Thread[t2,5,main]---i:6
Thread[t2,5,main]---i:7
Thread[t2,5,main]---i:8
Thread[t2,5,main]---i:9

7, common interview questions

The difference between processes and threads?

A: The process is the set of all threads, each thread is a path of execution process.

Why use multithreading?

A: The program to improve efficiency

Multithreading way to create?

A: Inheritance Thread or Runnable interface.

Using inheritance Thread class or Runnable interface that implement good?

A: Well implement Runnable interface, scalability inheritance is not strong, java total only supports single inheritance, if a class inheritance Thread class can not inherit the other.

Where do you use multithreading?

A: The main embody the multi-threaded program to improve efficiency.

Example: Batch send SMS messages.

8, concluded

We learned what a thread, the thread is a path of execution, each thread independently of each other;

Understand what is multi-threaded, multi-threaded in a single thread, a number of different execution paths, in parallel, the purpose of the program in order to improve efficiency.

Learn to create a common thread in two ways: inheritance Thread class implements the run method, or implement Runnable interface.

In fact, the actual development of these two methods is not common, but the use of thread pool to manage.

Learn thread of several states, new, ready, running, blocking, death.

Learn thread which is also a priority, with a scale of 1 to record, default is 5, the maximum is 10, set by calling setPriority (10) priority, the need to mention that not greater priority on You must first executed, but the probability of executing the priority should be large.

I created a java-related public number to record their own way of learning, and interested partners can look small micro-channel public number Kazakhstan: niceyoo

Guess you like

Origin blog.csdn.net/niceyoo/article/details/95116597