简体   繁体   中英

How do I instantiate two threads of the same object, and have the objects print different things

The goal: So I have a runnable class ThisThat. I instantiate two threads of ThisThat. One prints "This" and one prints "That". The main class is not supposed to determine what it prints.

The question: how do I make a default constructor set two different outputs for two threads of the same class? What can be improved? How can I make it only print this or that instead of both simultaneously?

Desired end result would be a program that runs for about 10 seconds and prints either this or that 10 times. Current output is "this" "that" at the same time, waits about 10 seconds and then repeats 10 times.

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接收任何东西,然后在ThisThat类中创建静态volatileAtomic属性,该属性基本上是一个计数器,用于更改每个线程实例的值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM