extends Thread直接创建
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Test {
static Logger logger = LogManager.getLogger(Test.class);
public static void main(String[] args) {
Thread t1 = new Thread("t1") {
@Override
public void run() {
logger.debug("thread name: {} {}", this.getName(), "hello juc");
}
};
t1.start();
}
}
劣势
- 需要继承,不灵活
implements Runnable再集合Thread创建
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Test {
static Logger logger = LogManager.getLogger(Test.class);
static class TestRunnable implements Runnable {
@Override
public void run() {
logger.debug("thread name: {} {}", Thread.currentThread().getName(), "hello juc");
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new TestRunnable(), "t2");
t1.start();
}
}
优势
- 可以配合线程池相关高级API用
- 跳出继承体系,灵活
implements Callable创建
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Test {
static Logger logger = LogManager.getLogger(Test.class);
static class TestCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
return 100;
}
}
public static void main(String[] args) {
FutureTask<Integer> futureTask = new FutureTask<Integer>(new TestCallable());
Thread t3 = new Thread(futureTask, "t3");
t3.start();
try {
logger.debug(futureTask.get());
} catch (Exception e) {
e.printStackTrace();
}
}
}
优势
-
跳出继承体系,灵活
-
有返回值
-
可以抛出异常
劣势
- get()方法其实有可能阻塞,需要等到线程运行完了才能拿到返回值