Java Concurrency (JUC) --- New threads and termination

Before entering the main content of Java concurrent programming, we start with a few basic concepts of concurrent programming start.

1. The difference between processes and threads:

Process: the smallest unit running resource allocation, there are multiple threads within a process, this process will share resources.
Thread: the smallest unit of CPU scheduling.
The need for the introduction of the thread: no thread before this concept, the process is the smallest unit of program resource allocation, but variable between processes is only one of the computer in this case is difficult to achieve shared between variables, this is difficult to achieve concurrently running program so much waste of CPU resources. Following the introduction of the thread, between different threads can share a single variable among the same process, not only to achieve a good run concurrently, but also makes the CPU utilization is greatly improved.

2. parallel and concurrent difference:

Parallel: the same time, what may have been the processing power of
concurrent: time-related units, the ability to deal with things in a unit of time (not necessarily at the same time)

For about a simple example:
You eat half a meal, phone, and you only have to pick up after eating, which means you do not support concurrent not support parallel.
You eat half a meal, phone, and you pick up the phone stopped, then continued after a meal, it shows your support for concurrency. (Not necessarily at the same time)
you eat half a meal, phone, and your phone while eating side, it shows your support parallel.

8 canteen Dafan windows may be simultaneously, each time Dafan 30s, the degree of parallelism of 8 canteen, canteen concurrency in one minute is 16.

3. Thread the new way (Java where the program is inherently multithreaded)

1) the Thread class: class inheritance, rewriting RUN (), newborn: new Thread (class) .start ()
Code:

package thread基础;

/**
 * @author lenovo
 */
public class StartAndRun {
    public static class ThreadRun extends Thread{
        @Override
        public void run() {
            int i=10;
            while(i>0){
                try {
                    Thread.sleep(1000);
                    System.out.println("I am "+Thread.currentThread().getName()
                            +" and now the i="+i--);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        ThreadRun beCalled=new ThreadRun();
        beCalled.setName("BeCalled");
        beCalled.run();
    }
}

operation result:
Here Insert Picture Description

2) Interface Runnable: implement the interface override run () newborn: new Thread (class) .start ()

3) Callable :( Interface implementation class interface can return a value, you can throw an exception)

Implementation of this class, override call ()

Freshmen: UseCall useCall = new UseCall () ; // UseCall Callable writing our own implementation class
a FutureTask, <> = a FutureTask, new new a FutureTask, <> (useCall);
new new the Thread (a FutureTask,) .start ();

Code Example 2 and 3:

package thread基础;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author lenovo
 */
public class NewThread {

    /**
     * 实现Runnable接口
     */
    private static class UseRun implements Runnable{

        @Override
        public void run() {
            System.out.println("I am implements Runnable");
        }
    }

    /**
     * 实现Callable接口
     */
    private static class UseCall implements Callable<String> {
        @Override
        public String  call() throws Exception {
            System.out.println("I am implements Callable");
            return "CallResult";
        }
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        UseRun useRun=new UseRun();
        new Thread(useRun).start();

        UseCall useCall=new UseCall();
        //FutureTask实现了Callable到Runnable的转换
        FutureTask<String> futureTask=new FutureTask<>(useCall);
        new Thread(futureTask).start();
        System.out.println(futureTask.get());

    }
}

operation result
Here Insert Picture Description

Difference: Runnable rewritable run () method returns no value, Callable rewritten call () method returns a value

4. thread termination:

1) stop () resume () suspend () ------> forced termination will not necessarily free up resources (the new version of the JDK has abandoned these methods, it is recommended that readers generally do not use)

2) java thread is cooperating (recommended to use the following method to interrupt the thread)

Note: The following methods are not forced to terminate a thread, it just sends a signal, we only process the signal processing logic thread to thread being interrupted in the true sense

interrupt () interrupts a thread, not forced to close this thread, just set the interrupt flag is true

isInterrupted (): determining whether the current thread interrupted state
** ------- "** provided by the class the Thread
interrupted under static method (): determines whether the interrupted state, the interrupt flag to false

Code Example:

package thread基础;

/**
 * @author lenovo
 */
public class EndThread {

    private static class UseThread extends Thread{

        public UseThread(String name){
            super(name);
        }

        @Override
        public void run() {
            String threadName=Thread.currentThread().getName();
            while (!isInterrupted()){
                System.out.println(threadName+" is run! ");
            }
            System.out.println(threadName+" interrupt flag is "+isInterrupted());
        }

        public static void main(String[] args) throws InterruptedException {
            Thread endThread=new UseThread("EndThread");
            endThread.start();
            Thread.sleep(1);
            endThread.interrupt();
        }
    }
}

Operating results
Here Insert Picture Description
Special Note: When the method of processing logic in our thread will throw InterruptedException, thread interrupt flag will be reset to false, we need to interrupt again from their catch in

Code Example:

package thread基础;

/**
 * @author lenovo
 */
public class HasInterruptException {
    public static class UseThread extends Thread{
        public UseThread(String name) {
            super(name);
        }
        @Override
        public void run() {
            String threadName=Thread.currentThread().getName();
            while(!isInterrupted()){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    System.out.println(threadName+" interrupt flag is "+isInterrupted());
                    e.printStackTrace();
                    interrupt();

                }
                System.out.println(threadName);
            }
            System.out.println(threadName+" interrupt flag is "+isInterrupted());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread=new UseThread("UseThread");
        thread.start();
        Thread.sleep(500);
        thread.interrupt();
    }
}

Operating results
Here Insert Picture Description
explained: because the processing logic thread has Thread.sleep (100); so it throws an exception InterruptedException its flag will be set to false, then we should manually interrupt the catch block in (), otherwise thread will not be interrupted

Published 19 original articles · won praise 2 · Views 422

Guess you like

Origin blog.csdn.net/TheWindOfSon/article/details/103328246