线程多次连接()一个线程

时间:2013-12-22 18:03:45

标签: java multithreading

我正在尝试使两个线程工作simultaneous。第一个应该每秒递增一个值,并将该值打印到屏幕。第二个,应该,每次增加一个值时,要求输入一些值,然后打印该值。

当我运行我的代码时,增量进展顺利,但是stdin只是问我一次输入,而不是简单的不再继续在repeater.join()上(但它会进入尝试)。

我的主要话题:

public class mainThread extends Thread
  {
    //global variables
public int contador=0;
public int maxcont=10;

public void incContador()
{
    this.contador++;
}

public void run()
{   
    Thread repeater = (new Thread(new repeatThread()));
    repeater.start();
    for(int i=0; i<maxcont; i++)
    {
        incContador();
        try{
            //It's asked to increment 1 unit each second
            Thread.sleep(1000);
        }catch(InterruptedException e){System.out.println("Deu erro!\n");}

        System.out.println(contador);
        try{
            //use my other thread
            repeater.join();
        }catch(InterruptedException e){System.out.println("Deu erro 2!\n");}
    }
} 



public static void main(String[] args)
{
    (new mainThread()).start();
}

}

我的转发帖线程

   public class repeatThread implements Runnable
   {
public void run()
{
    BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
    String s = "";
        try{
            s = buf.readLine();  
            System.out.println("Input is: "+s);

        }
        catch(IOException e){System.out.println("MyThreadRepeater - readLine() method error");}
    }




public static void main(String[] args) 
{
    (new Thread(new repeatThread())).start();
}
}

3 个答案:

答案 0 :(得分:0)

我相信你误解了Thread#join()的作用。这一行

repeater.join();

阻止您正在执行的当前线程,并等待repeater Thread表示的线程结束。

您的repeater Thread正在使用repeatThread对象,只需要输入一次和结束。

为什么您希望它能够提示用户提供更多输入?

答案 1 :(得分:0)

我没有完全回答你的问题。但是你的转发器代码只执行

BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
    String s = "";
        try{
            s = buf.readLine();  
            System.out.println("Input is: "+s);

        }
        catch(IOException e){System.out.println("MyThreadRepeater - readLine() method error");}
    }

代码只有一次。在循环中运行它以连续运行它。

答案 2 :(得分:0)

您的repeatThread只运行一次。如果你不想改变它的代码,你必须在每次迭代时创建新的repeatThread对象。我的意思是:

public void run()
{   
    for(int i=0; i<maxcont; i++)
    {
        Thread repeater = (new Thread(new repeatThread()));
        repeater.start();
        incContador();
        try{
            //It's asked to increment 1 unit each second
            Thread.sleep(1000);
        }catch(InterruptedException e){System.out.println("Deu erro!\n");}

        System.out.println(contador);
        try{
            //use my other thread
            repeater.join();
        }catch(InterruptedException e){System.out.println("Deu erro 2!\n");}
    }
} 

当您需要多个线程在特定点互相等待时,最好使用Barriers(例如CyclicBarrier)。我还应该提一下Thread.sleep(1000);可以保持线程至少休眠一秒钟,但不完全是。

相关问题