search
HomeJavajavaTutorialJava concurrent programming thread creation method:

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<V> callable)
        // 未来任务对象是啥,有啥用?
        //      -- 未来任务对象其实就是一个Runnable对象:这样就可以被包装成线程对象!
        //      -- 未来任务对象可以在线程执行完毕之后去得到线程执行的结果。
        FutureTask<String> 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<String>{
    // 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:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor