多线程执行任务

时间:2023-02-25 18:36:13

多线程并发执行任务

public class ThreadReadDataHub extends Thread {
protected static final Logger logger = LoggerFactory.getLogger(ThreadReadDataHub.class);
private Thread t;
private String threadName;
private String shardId;

public ThreadReadDataHub(String threadName, String shardId) {
this.threadName = threadName;
this.shardId = shardId;
}

public void run() {
logger.info("thread " + threadName + " shardId " + shardId + " is running");
try {


//编写自己的有任务逻辑

logger.info("**********************"+threadName+" is runing **********************");


} catch (Exception e) {
logger.info("thread " + threadName + " shardId " + shardId + " interrupted.");
}

logger.info("thread " + threadName + " shardId " + shardId + " exiting.");
}

public void start() {
logger.info("Starting " + threadName);
if (t == null) {
t = new Thread(this, threadName);
t.start();
}

}

}

调用

 String shardId = "0";
String name = "ThreadShardOne";
ThreadReadDataHub shardOne = new ThreadReadDataHub(name, shardId);
shardOne.start();

shardId = "1";
name = "ThreadShardTwo";
ThreadReadDataHub shardTwo = new ThreadReadDataHub(name, shardId);
shardTwo.start();