簡體   English   中英

如何實例化同一對象的兩個線程,並使對象打印不同的東西

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

目標:所以我有一個可運行的類ThisThat。 我實例化了ThisThat的兩個線程。 一個打印“ This”,另一個打印“ That”。 主類不應確定其打印內容。

問題:如何使默認構造函數為同一類的兩個線程設置兩個不同的輸出? 有什么可以改進的? 我怎樣才能使其僅打印此一個或那個而不同時打印兩個?

期望的最終結果將是一個程序運行大約10秒鍾,並打印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接收任何東西,然后在ThisThat類中創建靜態volatileAtomic屬性,該屬性基本上是一個計數器,用於更改每個線程實例的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM