package org.example.thread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CountDownLatch;
public class TestThead {
private static final String TAG = "TAG";
private static final Logger log = LoggerFactory.getLogger(TAG);
public static void main(String[] args) {
startTask();
}
public static void startTask(){
final CountDownLatch latch = new CountDownLatch(13);
for (int i = 1; i <= 13; i++) {
int j = i;
//启动java线程
new Thread(){
String distributionNo = String.valueOf(j);
String warehouseNo = String.valueOf(j);
String filename = String.format("data_%d.txt", j);
@Override
public void run() {
predict(distributionNo, warehouseNo, filename);
latch.countDown();
}
}.start();
}
try {
//log.debug("等待13个子线程执行完毕...");
latch.await();
log.debug("13个子线程已经执行完毕");
log.debug("回到主线程, 任务结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 这里填写之前预测的逻辑, 将编号改造成参数形式传入
* @param distributionNo
* @param warehouseNo
* @param filename
*/
public static void predict(String distributionNo, String warehouseNo, String filename) {
log.debug(String.format("distributionNo:%s, warehouseNo:%s, filename:%s", distributionNo, warehouseNo, filename));
}
}
log日志依赖:
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
执行结果:
10:35:55.515 [Thread-4] DEBUG TAG - distributionNo:5, warehouseNo:5, filename:data_5.txt
10:35:55.515 [Thread-6] DEBUG TAG - distributionNo:7, warehouseNo:7, filename:data_7.txt
10:35:55.515 [Thread-12] DEBUG TAG - distributionNo:13, warehouseNo:13, filename:data_13.txt
10:35:55.515 [Thread-5] DEBUG TAG - distributionNo:6, warehouseNo:6, filename:data_6.txt
10:35:55.515 [Thread-9] DEBUG TAG - distributionNo:10, warehouseNo:10, filename:data_10.txt
10:35:55.515 [Thread-0] DEBUG TAG - distributionNo:1, warehouseNo:1, filename:data_1.txt
10:35:55.515 [Thread-2] DEBUG TAG - distributionNo:3, warehouseNo:3, filename:data_3.txt
10:35:55.515 [Thread-11] DEBUG TAG - distributionNo:12, warehouseNo:12, filename:data_12.txt
10:35:55.515 [Thread-1] DEBUG TAG - distributionNo:2, warehouseNo:2, filename:data_2.txt
10:35:55.515 [Thread-8] DEBUG TAG - distributionNo:9, warehouseNo:9, filename:data_9.txt
10:35:55.515 [Thread-7] DEBUG TAG - distributionNo:8, warehouseNo:8, filename:data_8.txt
10:35:55.515 [Thread-10] DEBUG TAG - distributionNo:11, warehouseNo:11, filename:data_11.txt
10:35:55.515 [Thread-3] DEBUG TAG - distributionNo:4, warehouseNo:4, filename:data_4.txt
10:35:55.520 [main] DEBUG TAG - 13个子线程已经执行完毕
10:35:55.521 [main] DEBUG TAG - 回到主线程, 任务结束