[并发编程基础] Java线程的创建方式

简介: [并发编程基础] Java线程的创建方式

线程的创建方式

继承 Thread

  1. 创建一个继承 Thread 类的子类。
  2. 重写 Thread 类的 run() 方法。
  3. 在 run() 方法中编写线程要执行的任务。
  4. 创建 Thread 子类的对象。
  5. 调用 Thread 子类对象的 start() 方法来启动线程。
public class Demo {

    static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println(">>>> run ");
        }
    }

    public static void main(String[] args) {
        new MyThread().start();
        
    }
}

实现 Runnable 接口

  1. 创建一个实现 Runnable 接口的类。
  2. 在 Runnable 接口的 run() 方法中编写线程要执行的任务。
  3. 创建 Runnable 接口的实现类的对象。
  4. 将 Runnable 接口的实现类的对象传递给 Thread 类的构造方法来创建 Thread 对象。
  5. 调用 Thread 对象的 start() 方法来启动线程。
package org.example.create;

public class Demo1 {

    static class MyThread1 implements Runnable {
        @Override
        public void run() {
            System.out.println(">>>>> 2. 实现Runnable接口");
        }
    }

    public static void main(String[] args) throws Exception {
        new MyThread1().run();
        System.out.println("end");

    }
}

实现 Callable 接口

package org.example.create;

import java.util.concurrent.Callable;

public class Demo2 {

    static class MyThread implements Callable<Void> {
        @Override
        public Void call() throws Exception {
            System.out.println("3. 实现 Callable ");
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        new MyThread().call();
        System.out.println("end");

    }
}

使用 Lambda

package org.example.create;

public class Demo3 {


    public static void main(String[] args) throws Exception {
        new Thread(()->{
            System.out.println("4. 使用 lambda 表达式");
        }).run();
        System.out.println("end");

    }
}

使用线程池

package org.example.create;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo4 {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);

        // 创建Runnable对象
        Runnable runnable = () -> {
            // 线程的执行逻辑
            System.out.println(Thread.currentThread().getId() + "线程执行逻辑");
        };

        // 提交任务给线程池
        for (int i = 0; i < 50; i++) {
            executor.submit(runnable);
        }

        // 关闭线程池
        executor.shutdown();
    }

}

线程创建相关的 jdk源码

Thread

package java.lang;

public class Thread implements Runnable {
    /* Make sure registerNatives is the first thing <clinit> does. */
    private static native void registerNatives();
    static {
        registerNatives();
    }
}

Runnable函数接口


package java.lang;
/**
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.
This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread. Being active simply means that a thread has been started and has not yet been stopped.
In addition, Runnable provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.
Since:
1.0
See Also:
Thread, java.util.concurrent.Callable

**/
@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface {@code Runnable} is used
     * to create a thread, starting the thread causes the object's
     * {@code run} method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method {@code run} is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

Callable<V>函数接口


package java.util.concurrent;
/**
A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call.
The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.
The Executors class contains utility methods to convert from other common forms to Callable classes.
Since:
1.5
See Also:
Executor
Author:
Doug Lea
Type parameters:
<V> – the result type of method call
**/
@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

executors

package java.util.concurrent;
/**
Factory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes defined in this package. This class supports the following kinds of methods:
Methods that create and return an ExecutorService set up with commonly useful configuration settings.
Methods that create and return a ScheduledExecutorService set up with commonly useful configuration settings.
Methods that create and return a "wrapped" ExecutorService, that disables reconfiguration by making implementation-specific methods inaccessible.
Methods that create and return a ThreadFactory that sets newly created threads to a known state.
Methods that create and return a Callable out of other closure-like forms, so they can be used in execution methods requiring Callable.
Since:
1.5
Author:
Doug Lea
**/
public class Executors {}


相关文章
|
1天前
|
Java 调度
【JAVA学习之路 | 提高篇】线程的通信
【JAVA学习之路 | 提高篇】线程的通信
|
1天前
|
存储 Java
【JAVA学习之路 | 提高篇】线程安全问题及解决
【JAVA学习之路 | 提高篇】线程安全问题及解决
|
1天前
|
Java
【JAVA学习之路 | 提高篇】创建与启动线程之二(继承Thread类)(实现Runnable接口)
【JAVA学习之路 | 提高篇】创建与启动线程之二(继承Thread类)(实现Runnable接口)
|
1天前
|
Java 调度
【JAVA学习之路 | 提高篇】进程与线程(Thread)
【JAVA学习之路 | 提高篇】进程与线程(Thread)
|
1天前
|
Java 开发者
Java并发编程:理解线程同步和锁
【5月更文挑战第22天】本文将深入探讨Java并发编程的核心概念——线程同步和锁。我们将从基本的同步问题开始,逐步深入到更复杂的并发控制技术,包括可重入锁、读写锁以及Java并发工具库中的其他锁机制。通过理论与实例相结合的方式,读者将能够理解在多线程环境下如何保证数据的一致性和程序的正确性。
|
1天前
|
Java 程序员
Java中的多线程编程
本文将深入探讨Java中的多线程编程,包括线程的创建、启动、控制和同步等关键技术。我们将通过实例代码演示如何在Java中实现多线程,并讨论多线程编程的优势和挑战。
|
2天前
|
Java 容器
Java并发编程:深入理解线程池
【5月更文挑战第21天】 在多核处理器的普及下,并发编程成为了提高程序性能的重要手段。Java提供了丰富的并发工具,其中线程池是管理线程资源、提高系统响应速度和吞吐量的关键技术。本文将深入探讨线程池的核心原理、关键参数及其调优策略,并通过实例展示如何高效地使用线程池以优化Java应用的性能。
|
2天前
|
监控 算法 Java
Java并发编程:深入理解线程池
【5月更文挑战第21天】 在现代软件开发中,尤其是Java应用中,并发编程是一个不可忽视的重要领域。合理利用多线程可以显著提高程序的性能和响应速度。本文将深入探讨Java中的线程池机制,包括其工作原理、优势以及如何正确使用线程池来优化应用程序性能。通过分析线程池的核心参数配置,我们将了解如何根据不同的应用场景调整线程池策略,以期达到最佳的并发处理效果。
|
8天前
|
安全 Java
深入理解Java并发编程:线程安全与性能优化
【2月更文挑战第22天】在Java并发编程中,线程安全和性能优化是两个重要的主题。本文将深入探讨这两个主题,包括线程安全的基本概念,如何实现线程安全,以及如何在保证线程安全的同时进行性能优化。
20 0
|
4天前
|
安全 Java 容器
Java一分钟之-并发编程:线程安全的集合类
【5月更文挑战第19天】Java提供线程安全集合类以解决并发环境中的数据一致性问题。例如,Vector是线程安全但效率低;可以使用Collections.synchronizedXxx将ArrayList或HashMap同步;ConcurrentHashMap是高效线程安全的映射;CopyOnWriteArrayList和CopyOnWriteArraySet适合读多写少场景;LinkedBlockingQueue是生产者-消费者模型中的线程安全队列。注意,过度同步可能影响性能,应尽量减少共享状态并利用并发工具类。
18 2