Home  >  Article  >  Java  >  Java concurrent programming thread creation method:

Java concurrent programming thread creation method:

WBOY
WBOYforward
2023-05-09 13:01:071262browse

1. Threads and processes

A process is a running activity of code on a data collection. It is the basic unit of resource allocation and scheduling in the system. A thread is an entity. There is at least one thread in a process. , is the basic unit of CPU scheduling and allocation. Multiple threads in a process share the resources of the process.

Three characteristics of the process:

  • #Dynamicity: The process is a running program and needs to be occupied dynamically Resources such as memory, CPU and network.

  • Independence: Processes are independent of each other and have their own independent memory areas.

  • Concurrency: If the CPU is a single core, there is actually only one process being executed in the memory at the same time. The CPU will poll and switch in a time-sharing manner to serve each process in turn. Because the switching speed is very fast, it gives us the feeling that these processes are executing at the same time. This is concurrency.

2. Creation and running of threads

We have three ways to create threads in the process:

  • Method 1: How to inherit the Thread class

  • 1. Define a thread class to inherit the Thread class.

  • 2. Override the run() method

  • 3. Create a new thread object.

  • 4. Call the start() method of the thread object to start the thread.

public class ThreadDemo {
    // 启动后的ThreadDemo当成一个进程。
    // main方法是由主线程执行的,理解成main方法就是一个主线程
    public static void main(String[] args) {
        // 3.创建一个线程对象
        Thread t = new MyThread();
        // 4.调用线程对象的start()方法启动线程,最终还是执行run()方法!
        t.start();

        for(int i = 0 ; i < 100 ; i++ ){
            System.out.println("main线程输出:"+i);
        }
    }
}

// 1.定义一个线程类继承Thread类。
class MyThread extends Thread{
    // 2.重写run()方法
    @Override
    public void run() {
        // 线程的执行方法。
        for(int i = 0 ; i < 100 ; i++ ){
            System.out.println("子线程输出:"+i);
        }
    }
}

Advantages: The coding is simple, just use this directly to get the current thread in the run() method, without using the Thread.currentThread() method. Disadvantages: The thread class has inherited the Thread class and cannot inherit other classes, and functions cannot be expanded through inheritance (limitations of single inheritance). In addition, tasks and codes are not separated. When multiple threads perform the same task, multiple task codes are required.

Summary:

  • The thread class is a class that inherits Thread.

  • The start() method must be called to start the thread.

  • Multiple threads concurrently preempt CPU execution, so concurrency randomness will occur during the execution process

Method 2:How to implement the Runnable interface.

  • 1. Create a thread task class to implement the Runnable interface.

  • 2. Override the run() method

  • 3. Create a thread task object.

  • 4. Pack the thread task object into a thread object

  • 5. Call the start() method of the thread object to start the thread.

public class ThreadDemo {
    public static void main(String[] args) {
        // 3.创建一个线程任务对象(注意:线程任务对象不是线程对象,只是执行线程的任务的)
        Runnable target = new MyRunnable();
        // 4.把线程任务对象包装成线程对象.且可以指定线程名称
        // Thread t = new Thread(target);
        Thread t = new Thread(target,"1号线程");
        // 5.调用线程对象的start()方法启动线程
        t.start();

        Thread t2 = new Thread(target);
        // 调用线程对象的start()方法启动线程
        t2.start();

        for(int i = 0 ; i < 10 ; i++ ){
            System.out.println(Thread.currentThread().getName()+"==>"+i);
        }
    }
}

// 1.创建一个线程任务类实现Runnable接口。
class MyRunnable implements Runnable{
    // 2.重写run()方法
    @Override
    public void run() {
        for(int i = 0 ; i < 10 ; i++ ){
            System.out.println(Thread.currentThread().getName()+"==>"+i);
        }
    }
}

Advantages:

The thread task class only implements the Runnable interface, can continue to inherit other classes, and can continue to implement other interfaces (avoid (outside the limitations of single inheritance). The same thread task object can be packaged into multiple thread objects, suitable for multiple threads to share the same resource. To achieve decoupling operations, thread task code can be shared by multiple threads, and thread task code and threads are independent.

Method 3: Implement the Callable interface

  • 1. Define a thread task class to implement the Callable interface and declare the result type of thread execution.

  • 2. Rewrite the call method of the thread task class. This method can directly return the execution result.

  • 3. Create a Callable thread task object.

  • 4. Pack the Callable thread task object into a FutureTask object.

  • 5. Pack the FutureTask object into a thread object.

  • 6. Call the thread's start() method to start the thread.

public class ThreadDemo {
    public static void main(String[] args) {
        // 3.创建一个Callable的线程任务对象
        Callable call = new MyCallable();
        // 4.把Callable任务对象包装成一个未来任务对象
        //      -- public FutureTask(Callable callable)
        // 未来任务对象是啥,有啥用?
        //      -- 未来任务对象其实就是一个Runnable对象:这样就可以被包装成线程对象!
        //      -- 未来任务对象可以在线程执行完毕之后去得到线程执行的结果。
        FutureTask task = new FutureTask<>(call);
        // 5.把未来任务对象包装成线程对象
        Thread t = new Thread(task);
        // 6.启动线程对象
        t.start();

        for(int i = 1 ; i <= 10 ; i++ ){
            System.out.println(Thread.currentThread().getName()+" => " + i);
        }

        // 在最后去获取线程执行的结果,如果线程没有结果,让出CPU等线程执行完再来取结果
        try {
            String rs = task.get(); // 获取call方法返回的结果(正常/异常结果)
            System.out.println(rs);
        }  catch (Exception e) {
            e.printStackTrace();
        }

    }
}

// 1.创建一个线程任务类实现Callable接口,申明线程返回的结果类型
class MyCallable implements Callable{
    // 2.重写线程任务类的call方法!
    @Override
    public String call() throws Exception {
        // 需求:计算1-10的和返回
        int sum = 0 ;
        for(int i = 1 ; i <= 10 ; i++ ){
            System.out.println(Thread.currentThread().getName()+" => " + i);
            sum+=i;
        }
        return Thread.currentThread().getName()+"执行的结果是:"+sum;
    }
}

Advantages: The thread task class only implements the Callable interface, can continue to inherit other classes, and can continue to implement other interfaces (avoiding the limitations of single inheritance ). The same thread task object can be packaged into multiple thread objects, suitable for multiple threads to share the same resource. To achieve decoupling operations, thread task code can be shared by multiple threads, and thread task code and threads are independent. The most important thing is to be able to directly get the results of thread execution.

The above is the detailed content of Java concurrent programming thread creation method:. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete