在有些时候,单个线程执行的任务步骤会非常多,后一个步骤的输入可能是前一个步骤的输出,比如单个线程多步骤(阶段)执行时,为了使得功能单一,有时候我们会采用 GoF 职责链设计模式。
package concurrent.context.improve;
/**
* 线程运行上下文设计模式
* 上下文
*
* @author cakin
*/
public class Context {
private String name;
private String cardId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
}
/**
* 线程运行上下文设计模式
* 从数据库查询数据
*
* @author cakin
*/
public class QueryFromDbAction {
public void execute(Context context) {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
String name = "Alex-" + Thread.currentThread().getName();
context.setName(name);
}
}
package concurrent.context;
/**
* 线程运行上下文设计模式
* 调用接口获取数据
*
* @author cakin
*/
public class QueryFromHttpAction {
public void execute(Context context) {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
String name = context.getName();
String cardId = getCardId(name);
context.setCardId(cardId);
}
private String getCardId(String name) {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "510823" + Thread.currentThread().getId();
}
}
package concurrent.context;
/**
* 线程运行上下文设计模式
* 线程执行任务
*
* @author cakin
*/
public class ExecutionTask implements Runnable {
private QueryFromDbAction queryAction = new QueryFromDbAction();
private QueryFromHttpAction httpAction = new QueryFromHttpAction();
@Override
public void run() {
Context context = new Context();
queryAction.execute(context);
System.out.println("The name query successful.");
httpAction.execute(context);
System.out.println("The card id query successful.");
System.out.println("The Name is " + context.getName() + " and CardId is " + context.getCardId());
System.out.println(context);
}
}
package concurrent.context;
import java.util.stream.IntStream;
/**
* 线程运行上下文设计模式
* 上下文测试
*
* @author cakin
*/
public class ContextTest {
public static void main(String[] args) {
IntStream.rangeClosed(1, 4).forEach(i -> {
new Thread(new ExecutionTask(), "T" + i).start();
});
}
}
The name query successful.
The name query successful.
The name query successful.
The name query successful.
The card id query successful.
The card id query successful.
The Name is Alex-T2 and CardId is 51082313
The card id query successful.
The Name is Alex-T4 and CardId is 51082315
concurrent.context.Context@244c2a61
The card id query successful.
The Name is Alex-T3 and CardId is 51082314
concurrent.context.Context@1a712b8a
The Name is Alex-T1 and CardId is 51082312
concurrent.context.Context@7d67eaea
concurrent.context.Context@237cd6cd
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/chengqiuming/article/details/124355374
内容来源于网络,如有侵权,请联系作者删除!