适用于2个线程的Java Scanner

时间:2015-12-12 11:52:08

标签: java multithreading

我正在尝试构建一个程序,我想输入(使用Scanner)少数数字,如5,3,6,65,33,1,24,12,然后使用2个线程打印它们。第一个线程将打印从较低到较高,第二个线程将打印较高到较低。我会在这里写伪代码然后我会解释我的问题。

class tThread() extends Thread
{
  tThread(String name)
 {
   super(name);
   start();
 }

 public void run()
 {
   // here is Scanner

   //open try block
   if(getName().equals("Thread #1"))
  {
    //here I write data who print lower to higher 
  }
   else if(getName().equals("Thread #2"))
  {
    //here I write data who print higher to lower
  }
}


public class ThreadDemo
{
  public static void main(String[] args)
  {
    tThread t1 = new tThread("Thread #1");
    tThread t2 = new tThread("Thread #2");
  }

因为Scanner在run()方法中,并且因为我在main()中有2个线程, 当我运行这个项目时,我需要输入数据2次。如何仅将扫描器放在main中以仅请求一次输入,然后将输入发送到这两个线程?我知道也许我需要同步这2个线程,但这不是问题,我稍后会这样做。我想知道的是如何使用Scanner解决这个问题。

2 个答案:

答案 0 :(得分:1)

在您的班级中使用静态变量,并对其进行同步。

扫描并将数据放入其中。

在启动你的线程之前。

答案 1 :(得分:1)

没有什么可以阻止您通过Scanner将输入添加到main中的列表List<String>,然后将第二个参数添加到

的构造函数中
tThread(String name, List<String> input){
   super(name);
   this.inputList = input;
}

其中inputList是private和final而非static。

话虽如此,您的代码存在许多问题。我知道它是伪代码但要确保。不要在其构造函数中启动一个线程。 (有关详细说明,请参阅here。)

首选实现Runnable而不是扩展Thread并更喜欢使用threadPools而不是产生线程(至少在生产中)。

另外,不要将名称用作标记,而是创建runnables的不同实现,因为这样,如果添加第三种方法,则需要添加另一种方法。