首页 > 解决方案 > 如何实例化同一对象的两个线程,并让对象打印不同的东西

问题描述

目标:所以我有一个可运行的类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();
   }

 }

标签: javamultithreading

解决方案


一种解决方案是更新构造函数以不从 中获取任何内容,然后在您的类中Main创建一个静态volatile或属性,该属性基本上是一个更改每个线程实例值的计数器。AtomicThisThat


推荐阅读