java multithreading three kinds of implementation

Multithreading related issues

1. What is the process?

Program is being executed

2. What is the thread?

Sub-unit of the process, to complete the implementation of a path independent function

3. Why do you need to open multiple threads?

  • When the time-consuming operation to perform certain tasks need to open multiple threads to prevent thread blocking
  • You can make two tasks at the same time look like in execution
  • Increase CPU usage, and to improve processes and memory usage

4. Why can open multiple threads execute simultaneously?

Because the fast switching speed of the CPU's execution, the naked eye can not be gap

5. Turn Multithreading is not possible, to improve the efficiency or reduce the efficiency?

No, more threads, the slower the efficiency, but little waste of CPU resources, so the rational use of CPU

6. The difference between the parallel and concurrent

  • Concurrency -> simultaneous execution of multiple threads at the same time, looks like simultaneously executed
  • Parallel -> in the same timescale (can not be divided in units of time) executing a plurality of threads simultaneously executed is the inherently

CPU at a certain minimum time scale units, execution of a statement is not atomic subdivision of a thread of a process

Thread open the way

Java provides three methods to create threads:

1. Thread class inherits the way

2. To achieve Runnable way

3. Create a thread through Callable and Future.

Method 1: Thread class inheritance

1. Custom class MyThread inherit the Thread class. . 3
2.MyThread class which override run () method.
3. Create a thread object.
4. Start the thread.
Note:
1, start the thread using the start () method instead of run () method
2, multiple threads can not start

Thread object and calls the run method calls the difference between the start method?

  • Thread object calls the run method is not open thread. Only the object method call.
  • Open thread object start calling thread and let jvm calls the run method of execution in the open thread

Code demonstrates use an open thread

// 方式二:实现Runnable接口
class CalculateRunnable implements Runnable {
    private int m;
    private int n;
    public CalculateRunnable(int m, int n) {
        super();
        this.m = m;
        this.n = n;
    }
    public CalculateRunnable() {
        super();
    }
    @Override
    public void run() {
        int sum = 0;
        for (int i = m; i <= n; i++) {
            sum += i;
            System.out.println("CalculateRunnable子线程: " + i);
        }
        System.out.println(m + "~" + n + "的和: " + sum);
    }
} 

Second way: implement Runnable

1. custom class MyRunnable implement Runnable
2. override run () method
3. MyRunnable create an object class
4. Create Thread class objects, and the object is created in step 3 as the configuration parameter passing
5. start a thread

The benefits of implementing the interface method
can avoid the Java single inheritance brings limitations.
A plurality of the same program code adapted to handle a case where the same resource, the thread with the code of the program, data effective separation, preferably reflects the object-oriented design.

Code demonstrates two ways open thread

// 方式一:继承Thread类
class CopyThread extends Thread {
    private File srcFile;
    private File descFile;
    
    public CopyThread() {
        super();
    }

    public CopyThread(File srcFile, File descFile) {
        super();
        this.srcFile = srcFile;
        this.descFile = descFile;
    }

    @Override
    public void run() {
        // main方法怎么写,这里就怎么写
        copy(srcFile, descFile);
    }

    public void copy(File srcFile, File descFile) {
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(descFile))){
            byte[] bys = new byte[1024];
            int len = 0;
            while ((len = bis.read(bys)) != -1) {
                bos.write(bys, 0, len);
                bos.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Main method calls
    public static void main(String[] args) {
        CopyThread ct = new CopyThread(new File("Test.java"), new File("Test.txt"));
        CalculateRunnable cr = new CalculateRunnable(1, 200);
        Thread t = new Thread(cr);
        ct.start();
        t.start();
        for (int i = 0; i < 100; i++) {
            System.out.println("main线程: " + i);
        }
    }

Three ways: Callable and Future create a thread.

  • Create Callable interface implementation class, and implements call () method, the call () method as a thread of execution, and return values.
  • Callable create an instance of the implementation class, using packaging Callable FutureTask class object, which object encapsulates FutureTask Callable object of the call () method returns the value.
  • Use FutureTask Thread object as a target object to create and start a new thread.
  • Call FutureTask object get () method to obtain the return value after the end of the sub-thread execution.

Thread achieve Runnable inheritance and way of features:

1. does not return results

2. No abnormal

Callable and Runnable difference:

1.Runnable no return value, no exceptions thrown

2.Callable can get value in return start threads, and accept the abnormal child threads

Data transfer between the thread: thread communication

A thread opened a thread B

A -> B via the constructor

B -> A by way Callable

public class CallableDemo{
    public static void main(String[] args) {
        FutureTask<Integer> task = new FutureTask<>(new CalculateCallable(0,100));
        Thread t = new Thread(task);
        t.start();
        
        try {
            Integer i = task.get();
            System.out.println("计算结果: " + i);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        System.out.println("程序结束");
    }
}
class CalculateCallable implements Callable<Integer> {
    
    private int m;
    private int n;
    
    public CalculateCallable() {
        super();
    }
    
    public CalculateCallable(int m, int n) {
        super();
        this.m = m;
        this.n = n;
    }

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = m; i <= n; i++) {
            System.out.println("子线程: " + i);
            sum += i;
            throw new NullPointerException("空指针异常!");
        }
        return sum;
    }
}

Guess you like

Origin www.cnblogs.com/zhiwenxi/p/11407857.html