java - 如何实例化同一对象的两个线程,并让对象打印不同的东西
问题描述
目标:所以我有一个可运行的类ThisThat。我实例化了 ThisThat 的两个线程。一个打印“This”,一个打印“That”。主类不应该确定它打印的内容。
问题:如何让默认构造函数为同一类的两个线程设置两个不同的输出?有什么可以改进的?我怎样才能让它只打印这个或那个而不是同时打印?
期望的最终结果将是一个运行大约 10 秒并打印这个或那个 10 次的程序。当前输出同时为“this”“that”,等待10秒左右,然后重复10次。
import java.util.Random;
public class ThisThat implements Runnable {
private String output;
private int threadNum;
public ThisThat() {
output = "";
}
public ThisThat(int t_Num) {
threadNum = t_Num;
setThisOrThat(threadNum);
}
public void setThisOrThat(int num) {
if (num == 1) {
output = "this";
} else if (num == 2) {
output = "that";
} else {
Random random = new Random();
int randNum = random.nextInt((3) + 1);
setThisOrThat(randNum);
}
}
@Override
public void run() {
for (int i=1; i <= 10; i++) {
try {
System.out.println(getOutput());
Thread.sleep((int)(800));
}
catch(InterruptedException e) {
System.err.println(e);
}
}
}
public String getOutput() { return output; }
public void setOutput(String output) { this.output = output; }
}
class Main {
public static void main(String args[]) {
Thread thread1 = new Thread(new ThisThat(1));
Thread thread2 = new Thread(new ThisThat(2));
thread1.start();
thread2.start();
}
}
解决方案
一种解决方案是更新构造函数以不从 中获取任何内容,然后在您的类中Main
创建一个静态volatile
或属性,该属性基本上是一个更改每个线程实例值的计数器。Atomic
ThisThat
推荐阅读
- c - 如何在 C 中出现此错误:'printf' 的参数 1 的类型不兼容
- go - protobuf 消息字段 id 和字段顺序的关系是什么?
- kubernetes - 成功完成后自动删除 Argo 工作流
- php - 如何使用 php 7.3 在 html 页面上运行 php
- python - 如何自定义条形注释以不显示所选值
- python - PyTorch LSTM 正在预测训练数据集
- npm - 包含来自另一个文件的 package.json 依赖项
- javascript - 如何使用 Php 将新对象推送到 Js 中的数组中
- c# - Oracle 阻止 NET6 迁移 - 检测到超出依赖约束的包版本
- git - “git push --force”是否会推送存储库中的所有对象?