Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用于2个线程的Java扫描程序_Java_Multithreading - Fatal编程技术网

用于2个线程的Java扫描程序

用于2个线程的Java扫描程序,java,multithreading,Java,Multithreading,我正试图建立一个程序,我想输入(使用扫描仪)一些数字,如5,3,6,65,33,1,24,12,然后用两个线程打印它们。第一个线程将从低到高打印,第二个线程将从高到低打印。我将在这里编写伪代码,然后解释我的问题 class tThread() extends Thread { tThread(String name) { super(name); start(); } public void run() { // here is Scanner //ope

我正试图建立一个程序,我想输入(使用扫描仪)一些数字,如5,3,6,65,33,1,24,12,然后用两个线程打印它们。第一个线程将从低到高打印,第二个线程将从高到低打印。我将在这里编写伪代码,然后解释我的问题

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()中有两个线程,
当我运行这个项目时,我需要输入两次数据。如何将Scanner only放在main中,只请求一次输入,然后将输入发送到这两个线程?我知道我可能需要同步这两个线程,但这不是问题,我会稍后再做。我只想知道如何用Scanner解决这个问题。

在类中使用静态变量,并将其同步

扫描并将数据放入其中


在启动线程之前。

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

tThread(String name, List<String> input){
   super(name);
   this.inputList = input;
}
tThread(字符串名称,列表输入){
超级(姓名);
this.inputList=输入;
}
其中inputList是私有的、最终的,而不是静态的

也就是说,您的代码存在许多问题。我知道这是伪代码,但要确定。不要在其构造函数中启动线程。(有关详细说明,请参见)

更喜欢实现
Runnable
而不是扩展
Thread
,更喜欢threadpool而不是生成线程(至少在生产环境中)


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

感谢您的建议,我尝试按照您的示例进行操作,但后来在代码中迷失了方向。我尝试了纪尧姆·吉罗德·维图奇基纳所说的话,并取得了成效。我还要感谢您告诉我代码中的问题,因为我不知道这一点。我的老师在课堂上给我们举了这样的例子,我认为这是一种“专业的方式”。没问题。在这种特殊情况下,建议的方法非常有效,但是在大的情况下,如果您有一个更改来安全地避免同步,您应该尝试一下。关于你们老师的建议,我还并没有看到,所以我不能说什么,只能注意关于在构造函数中启动线程的建议。