Java如何通过Thread创建多线程测试程序(不包括线程池)

1 缘起

每次想使用多线程测试脚本时,总会忘记线程池的参数(我的脑袋没有太好用吧,就忘),
但是,我又想使用多线程测试,所以,想单纯的测试,是不是有简便的方法。
当然有。直接new Thread()。
曾经有和同事聊过,多线程编程,他们比较鄙视直接new Thread(),我也不知道为什么。
难道说使用线程池才会体现高级吗?
当然,高级就高级吧。
其实,我只是做一个脚本测试,不在后台生产环境跑服务,
所以,就直接使用new Thread(),比较方便。
这里不介绍线程池,只总结了Thread的几种使用方式。

2 如何启动线程

由Thread类可知,启用线程的方法为start(),即:new Thread().start()
start方法执行时其实有两个线程工作。
执行start的为当前线程,执行run方法的为另一个线程,即通过new Thread()创建的线程。
从何而知:源码。下面是start()方法的源码注释截图及源码,通过注释可知,如上所述。
在这里插入图片描述

start源码:java.lang.Thread#start


    /**
     * Causes this thread to begin execution; the Java Virtual Machine
     * calls the <code>run</code> method of this thread.
     * <p>
     * The result is that two threads are running concurrently: the
     * current thread (which returns from the call to the
     * <code>start</code> method) and the other thread (which executes its
     * <code>run</code> method).
     * <p>
     * It is never legal to start a thread more than once.
     * In particular, a thread may not be restarted once it has completed
     * execution.
     *
     * @exception  IllegalThreadStateException  if the thread was already
     *               started.
     * @see        #run()
     * @see        #stop()
     */
    public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        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 */
            }
        }
    }

3 测试

3.1 直接继承Thread

直接继承Thread类,需要重写run方法,在run方法里自定义逻辑。

package com.monkey.java_study.thread.pure_thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 继承Thread.
 *
 * @author xindaqi
 * @date 2022-04-21 11:24
 */
public class ExtendsThread extends Thread {

    private static final Logger logger = LoggerFactory.getLogger(ExtendsThread.class);

    private String threadName;

    public void setThreadName(String threadName) {
        this.threadName = threadName;
    }

    public String getThreadName() {
        return threadName;
    }

    public ExtendsThread() {

    }

    public ExtendsThread(String threadName) {
        super(threadName);
    }

    @Override
    public void run() {
        logger.info(">>>>>>>>>Extends Thread and Body in run, Thread name:{}", Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        Thread t1 = new ExtendsThread("t1");
        Thread t2 = new ExtendsThread("t2");

        t1.start();
        t2.start();
    }
}
  • 运行结果
    在这里插入图片描述

3.2 直接在Thread中直接写逻辑

如果不继承Thread如何自定义多线程呢?
Thread类的方法比较丰富,可以直接在Thread中填写逻辑。
调用的Thread方法为:java.lang.Thread#Thread(java.lang.Runnable, java.lang.String)
源码截图如下,通过构建第一个参数,初始化线程,使用语法()->,构建Runnable。
当然,有人会说,既然是Runnable类型的参数,为什么直接使用Runnable,
这可,可以,后面讲。
在这里插入图片描述

package com.monkey.java_study.thread.pure_thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 逻辑直接在Thread中.
 *
 * @author xindaqi
 * @date 2022-04-21 11:23
 */
public class BodyInThread {

    private static final Logger logger = LoggerFactory.getLogger(BodyInThread.class);

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            logger.info(">>>>>>>>Body in thread, Thread name:{}", Thread.currentThread().getName());
            logger.info(">>>>>>>>");
        }, "t1");

        Thread t2 = new Thread(() -> {
            logger.info(">>>>>>>>Body in thread, Thread name:{}", Thread.currentThread().getName());
            logger.info(">>>>>>>>");
        }, "t2");

        t1.start();
        t2.start();
    }
}
  • 运行结果
    在这里插入图片描述

3.3 在Thread中调用方法

同样地,在Thread中可以直接写逻辑,也可以通过独立的方法实现逻辑,与上面一样:
调用的Thread方法为:java.lang.Thread#Thread(java.lang.Runnable, java.lang.String)
构建Runnable两种方式:语法::执行方法,或者()->。

package com.monkey.java_study.thread.pure_thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Thread中调用方法.
 *
 * @author xindaqi
 * @date 2022-04-21 11:23
 */
public class MethodInThread {

    private static final Logger logger = LoggerFactory.getLogger(MethodInThread.class);

    public static void methodTest() {
        logger.info(">>>>>>>>Method in thread, Thread name:{}", Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(MethodInThread::methodTest, "t1");
        Thread t2 = new Thread(() -> methodTest(), "t2");
        t1.start();
        t2.start();
    }
}
  • 运行结果
    在这里插入图片描述

3.4 实现Runnable

好了,这里是直接使用Runnable初始化线程,即实现Runnable接口,
初始化线程时,直接传入实例化的类即可。
同时,需要重写run方法,实现自定义逻辑。
当前的实现方式,以及上面的方法,线程执行的逻辑均没有返回值,
即多线程执行的方法无法获取方法返回值。

package com.monkey.java_study.thread.pure_thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Runnable在Thread中.
 *
 * @author xindaqi
 * @date 2022-04-21 11:42
 */
public class RunnableInThread implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(RunnableInThread.class);

    @Override
    public void run() {
        logger.info(">>>>>>>>Runnable in run, Thread name:{}", Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new RunnableInThread(), "t1");
        Thread t2 = new Thread(new RunnableInThread(), "t2");
        Thread t3 = new Thread(new RunnableInThread(), "t3");

        t1.start();
        t2.start();
        t3.start();
    }
}
  • 运行结果
    在这里插入图片描述

3.5 实现Callable

如果多线程需要获取返回值应该怎么办?
有没有方案?
有。实现Callable接口。
该接口通过FutureTask接口获取方法返回结果,FutureTask作为参数初始化Thread。
同样调用:java.lang.Thread#Thread(java.lang.Runnable, java.lang.String)
因此,FutureTask的层次接口中必定实现了Runnable接口。
FutureTask实现了RunnableFuture,RunnableFuture实现了Runnable和Future。
java.util.concurrent.FutureTask
在这里插入图片描述
java.util.concurrent.RunnableFuture
在这里插入图片描述

package com.monkey.java_study.thread.pure_thread;

import jdk.nashorn.internal.codegen.CompilerConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * Callable在Thread中.
 *
 * @author xindaqi
 * @date 2022-04-21 11:46
 */
public class CallableInThread implements Callable<String> {

    private static final Logger logger = LoggerFactory.getLogger(CallableInThread.class);

    @Override
    public String call() throws Exception {
        logger.info(">>>>>>>>Callable in call, Thread name:{}", Thread.currentThread().getName());
        return Thread.currentThread().getName();
    }

    public static void main(String[] args) throws Exception {
        Callable<String> callable1 = new CallableInThread();
        FutureTask<String> futureTask1 = new FutureTask<>(callable1);
        FutureTask<String> futureTask2 = new FutureTask<>(callable1);
        FutureTask<String> futureTask3 = new FutureTask<>(callable1);
        Thread t1 = new Thread(futureTask1, "t1");
        Thread t2 = new Thread(futureTask2, "t2");
        Thread t3 = new Thread(futureTask3, "t3");

        t1.start();
        logger.info(">>>>>>>>Thread1 result:{}", futureTask1.get());
        t2.start();
        logger.info(">>>>>>>>Thread2 result:{}", futureTask2.get());
        t3.start();
        logger.info(">>>>>>>>Thread3 result:{}", futureTask3.get());
    }
}
  • 运行结果

在这里插入图片描述

4 小结

  • Java通过Thread创建线程可分为4类:
    (1)继承Thread,重写run方法;
    (2)在Thread中写方法,构建Runnable类型,通过::或者()->构建;
    (3)实现Runnable接口,重写run方法;
    (4)实现Callable接口,重写call方法。
  • 前三类无法获取方法返回值,第四类可以获取方法返回值。
  • 启动线程使用start方法,该方法执行时有两个线程工作,即调用start的当前线程和调用run方法的其他线程(new Thread创建的线程)。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java创建线程池时,可以使用 ThreadPoolExecutor 类来进行操作。ThreadPoolExecutor 类提供了多个构造函数来设置不同的参数。以下是几个常用的参数: 1. corePoolSize:线程池的核心线程数,即线程池中保持活动状态的线程数。如果提交的任务数量少于核心线程数,线程池创建新的线程来执行任务,即使有空闲线程。默认情况下,核心线程数为 0。 2. maximumPoolSize:线程池允许的最大线程数。如果提交的任务数量大于核心线程数,且等待队列已满,那么线程池创建新的线程来执行任务,直到达到最大线程数。默认情况下,最大线程数为 Integer.MAX_VALUE。 3. keepAliveTime:非核心线程的空闲时间超过该值后会被终止。默认情况下,非核心线程会一直保持活动状态,即使没有任务执行。 4. unit:keepAliveTime 的时间单位。可以使用 TimeUnit 类提供的常量来指定,如 TimeUnit.SECONDS。 5. workQueue:用于保存等待执行的任务的阻塞队列。常用的实现类有 ArrayBlockingQueue、LinkedBlockingQueue 和 SynchronousQueue。 6. threadFactory:用于创建新线程的工厂。可以自定义实现 ThreadFactory 接口来定制线程的属性,如线程名称、优先级等。 7. handler:当线程池和工作队列都满了,并且无法处理新的任务时,用于处理新提交的任务的策略。常用的策略有 ThreadPoolExecutor.AbortPolicy(默认,抛出异常)、ThreadPoolExecutor.CallerRunsPolicy(使用调用者线程执行任务)、ThreadPoolExecutor.DiscardPolicy(丢弃任务)和 ThreadPoolExecutor.DiscardOldestPolicy(丢弃最早的任务)。 这些参数可以根据具体需求进行调整,以满足对线程池的性能和资源控制的要求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天然玩家

坚持才能做到极致

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值