线程创建的3种方法
方法一: thread
方法二:使用 runnable
方法三:FutureTask配合Thread
futureTask能够接收Callable类型参数,用来处理有返回结果的情况
多个线程并行交替执行
package com.example.concurrency;
import lombok.extern.slf4j.Slf4j;
/**
* 演示多个线程并发交替执行
*/
@Slf4j(topic = "c.test")
public class MultiThreadTest {
public static void main(String[] args) {
Thread t1 = new Thread() {
@Override
public void run() {
while (true){
log.debug("running....");
}
}
};
t1.setName("t1");
t1.start();
Thread t2 = new Thread() {
@Override
public void run() {
while (true){
log.debug("running....");
}
}
};
t2.setName("t2");
t2.start();
Thread t3 = new Thread() {
@Override
public void run() {
while (true){
log.debug("running....");
}
}
};
t3.setName("t3");
t3.start();
打印…
20:53:35.349 [t2] DEBUG c.test - running....
20:53:35.349 [t2] DEBUG c.test - running....
20:53:35.349 [t2] DEBUG c.test - running....
20:53:35.349 [t2] DEBUG c.test - running....
20:53:35.349 [t2] DEBUG c.test - running....
20:53:35.348 [t3] DEBUG c.test - running....
20:53:35.349 [t3] DEBUG c.test - running....
20:53:35.349 [t3] DEBUG c.test - running....
20:53:35.349 [t3] DEBUG c.test - running....
20:53:35.349 [t3] DEBUG c.test - running....
20:53:35.349 [t3] DEBUG c.test - running....