准备工作:
pom.xml
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
在resource目录下面放入slf4j配置文件
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration
xmlns="http://ch.qos.logback/xml/ns/logback"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://ch.qos.logback/xml/ns/logback logback.xsd">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%date{HH:mm:ss} [%t] %logger - %m%n</pattern>
</encoder>
</appender>
<logger name="c" level="debug" additivity="false">
<appender-ref ref="STDOUT"/>
</logger>
<root level="ERROR">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
1. 方法一,直接使用 Thread
代码:
import lombok.extern.slf4j.Slf4j;
@Slf4j(topic = "c.Test1")
public class Test1 {
public static void main(String[] args) {
Thread t = new Thread() {
@Override
public void run() {
log.debug("t1 running");
}
};
t.setName("t1");
t.start();
log.debug("main running");
}
}
运行结果:
2. 方法二,使用Runnable配合Thread
代码:
import lombok.extern.slf4j.Slf4j;
@Slf4j(topic = "c.Test2")
public class Test2 {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
log.debug("t2 running");
}
};
Thread t = new Thread(r, "t2");
t.start();
log.debug("main running");
}
}
结果:
3. Java 8以后可以使用lambda精简代码
Runnable接口里面有一个@FunctionalInterface注解,说明这个接口可以被lamda表达式简化。(注意:@FunctionalInterface存在只有一个方法的接口中)
代码:
import lombok.extern.slf4j.Slf4j;
@Slf4j(topic = "c.Test2")
public class Test2 {
public static void main(String[] args) {
Runnable r = () -> log.debug("t1 running");
Thread t1 = new Thread(r, "t1");
t1.start();
new Thread(() -> log.debug("t2 running"), "t2").start();
log.debug("main running");
}
}
运行结果:
4. 小结
5. 补充 Java之使用Callable创建线程(了解即可)
Java之使用Callable创建线程(了解即可)
|