每次想使用多线程测试脚本时,总会忘记线程池的参数(我的脑袋没有太好用吧,就忘),
但是,我又想使用多线程测试,所以,想单纯的测试,是不是有简便的方法。
当然有。直接new Thread()。
曾经有和同事聊过,多线程编程,他们比较鄙视直接new Thread(),我也不知道为什么。
难道说使用线程池才会体现高级吗?
当然,高级就高级吧。
其实,我只是做一个脚本测试,不在后台生产环境跑服务,
所以,就直接使用new Thread(),比较方便。
这里不介绍线程池,只总结了Thread的几种使用方式。
由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 run
method of this thread.
*
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* start
method) and the other thread (which executes its
* run
method).
*
* 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创建的线程)。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)