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?
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(); } }