从线程工厂到线程

本文介绍了从线程工厂到线程的概念。线程工厂用于创建线程,线程参数包括线程组、目标对象、线程名和堆栈大小。线程的run方法在启动时被调用,线程一旦启动只能执行一次,不能重启。文章还简述了线程的六个状态。
摘要由CSDN通过智能技术生成

从线程工厂到线程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ME3woaF0-1615730486712)(C:\Users\10374\AppData\Roaming\Typora\typora-user-images\image-20210314203351846.png)]

工厂模式中有四个角色:

  • Factory:抽象的工厂
  • Product:抽象的零件
  • 具体的实现工厂
  • 具体的实现零件

上图就是一个工厂模式。

线程池是一个工厂,线程是线程池中的零件。

抽象工厂

public interface ThreadFactory {

    /**
     * Constructs a new {@code Thread}.  Implementations may also initialize
     * priority, name, daemon status, {@code ThreadGroup}, etc.
     *
     * @param r a runnable to be executed by new thread instance
     * @return constructed thread, or {@code null} if the request to
     *         create a thread is rejected
     */
    Thread newThread(Runnable r);
}

该线程工厂中有一个方法为生产一个新的线程。

线程工厂

static class DefaultThreadFactory implements ThreadFactory {
    //线程池大小为1
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    //线程组
    private final ThreadGroup group;
    //线程数
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    //名字的前缀
    private final String namePrefix;

    DefaultThreadFactory() {
        //安全管理
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                              Thread.currentThread().getThreadGroup();
        namePrefix = "pool-" +
                      poolNumber.getAndIncrement() +
                     "-thread-";
    }

    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                              namePrefix + threadNumber.getAndIncrement(),
                              0);
        if (t.isDaemon())
            t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }
}

创建新线程,设置为用户线程,和默认的线程优先级。

线程

group – the thread group. If null and there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager or SecurityManager.getThreadGroup() returns null, the group is set to the current thread’s thread group.

线程组

target – the object whose run method is invoked when this thread is started. If null, this thread’s run method is invoked.

调用的run方法

name – the name of the new thread

线程名字

stackSize – the desired stack size for the new thread, or zero to indicate that this parameter is to be ignored.

堆栈大小

public Thread(ThreadGroup group, Runnable target, String name,
              long stackSize) {
    init(group, target, name, stackSize);
}

线程的参数

 public final static int MIN_PRIORITY = 1;

/**
  * The default priority that is assigned to a thread.
  */
 public final static int NORM_PRIORITY = 5;

 /**
  * The maximum priority that a thread can have.
  */
 public final static int MAX_PRIORITY = 10;

线程优先级为1-10,5为默认优先级。

//是否 为守护线程
private boolean     daemon = false;

//run方法
private Runnable target;

//线程的线程组
private ThreadGroup group;

//上下文类加载器
private ClassLoader contextClassLoader;

/* For autonumbering anonymous threads. */
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
    return threadInitNumber++;
}

/* ThreadLocal values pertaining to this thread. This map is maintained
 * by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;

/*
 * InheritableThreadLocal values pertaining to this thread. This map is
 * maintained by the InheritableThreadLocal class.
 */
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

//堆栈值
private long stackSize;

/*
 * JVM-private state that persists after native thread termination.
 */
private long nativeParkEventPointer;

//线程ID
private long tid;

//线程生成ID
private static long threadSeqNumber;

/* Java thread status for tools,
 * initialized to indicate thread 'not yet started'
 */

private volatile int threadStatus = 0;

Run和Start方法

//从线程开始执行,JAVA虚拟机会调用该线程的run方法,然后两个线程同时执行
//线程只能启动一次,完成后不能重新启动
public synchronized void start() {

    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    /* Notify the group that this thread is about to be started
     * so that it can be added to the group's list of threads
     * and the group's unstarted count can be decremented. */
    group.add(this);

    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            /* do nothing. If start0 threw a Throwable then
              it will be passed up the call stack */
        }
    }
}

private native void start0();
//线程是单独的一个Runnable对象,则会被调用,否则不做任何事情
@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

从线程开始执行,jvm会调用该线程的run方法,然后两个线程同时执行
线程只能启动一次,完成后不能重新启动

线程启动调用了start0的本地方法,所以是jvm来调用的

线程的状态

public enum State {
    //线程的初始态
    NEW,

    //运行态
    RUNNABLE,

    //阻塞态
    BLOCKED,

    //等待
    WAITING,

    //等待超时
    TIMED_WAITING,

    //终止态
    TERMINATED;
}

线程的6个状态。

线程工厂ThreadFactory)是Java中用于创建线程的一个接口,它提供了一种标准的方式来替换Thread类的默认构造方法。通过线程工厂,开发者可以定制线程的创建过程,例如设置线程的名称、优先级、是否为守护线程等属性,甚至可以创建特定的线程实现。 在Java中,线程工厂通常与线程池(ExecutorService)结合使用。当执行器(Executor)需要创建新的线程时,它会调用线程工厂的newThread方法来创建线程。这样,开发者可以利用线程工厂来实现以下功能: 1. 自定义线程属性:通过线程工厂,可以设置新创建的线程的名称、优先级或是否为守护线程等属性,使其与应用程序的需求相匹配。 2. 线程池的线程监控:自定义的线程工厂可以跟踪线程的创建和使用情况,有助于监控和调试。 3. 异常处理:在自定义线程工厂中可以添加异常处理逻辑,例如在创建线程失败时进行日志记录或执行一些清理工作。 一个简单的线程工厂实现示例如下: ```java import java.util.concurrent.ThreadFactory; public class CustomThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); // 设置线程的属性 t.setName("CustomThread"); t.setDaemon(false); t.setPriority(Thread.NORM_PRIORITY); return t; } } ``` 当使用这种自定义的线程工厂线程池结合时,线程池就会使用`newThread`方法来创建线程
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值