2012-03-31 91 views
1

我试图编写一个使用线程但无法理解o/p的程序。我有2个线程:st。但我看不到线程s正在工作。线程行为:Java初学者

任何人都可以向我解释行为吗?由于

我的代码:

public class Bground implements Runnable 
{ 
    Thread t,s; 

    Bground() 
    { 
     t = new Thread(this,"first thread"); 
     s = new Thread(this,"second thread"); 

     s.start(); 
     t.start(); 
    } 

    public void run() 
    { 
     System.out.println("inside run" + t.getName()); 
     try 
     { 
      for (int i = 0; i < 5; i++) 
      { 
       System.out.println("In child thread" + i); 
      } 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
    } 

    public static void main(String argv[]) 
    { 
     Bground b = new Bground(); 
     try 
     {     
      for (int i = 0; i < 5; i++) 
      { 
       System.out.println("In main thread" + i); 
       Thread.sleep(1); 
      } 
     } 
     catch(InterruptedException e) 
     { 
      e.printStackTrace(); 
     } 
    } 
} 

O/P:

C:\ Program Files文件\的Java \ jdk1.6.0_23 \ BIN>的Java Bground

在主thread0
里面runfirst线程
里面runfirst线程
在子线程0
在子线程1
在子线程2
在主线程1
在孩子thread3
在孩子thread0
在子线程1
在子线程2
在孩子thread3
在孩子thread4
在主线程2
在子线程中4
在主线程中3
在主线程4

+5

只是为了让你知道:每当你像这样设计你的代码时,上帝杀死了一只小猫。 – 2012-03-31 01:00:43

+0

考虑让每个线程都有一个'Thread.sleep(1000)'。该参数以毫秒为单位。 – 2012-03-31 01:04:00

回答

2

你有什么期望将打印出带有:

System.out.println("inside run " + t.getName()); 

你不在这里,获取当前线程的名字,而是你总是给我t-Thread的名字。要修复 - 获取当前线程并致电getName()就可以了。

+0

是啊,对不起,这是愚蠢的..我证明了一个初学者,力我? :) – RVP 2012-03-31 01:10:38

2

您正在打印两次线程“t”的名称。那就是问题所在。另一方面线程似乎对我有用。 你可能想使用此代码来代替:

import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 


public class Bground implements Runnable { 
int name; 

Bground(int name) { 
    this.name=name; 
} 

public void run() { 
    System.out.println("inside run" + name); 
    try { 
     for (int i = 0; i < 5; i++) { 
      System.out.println("In child thread" + i); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

public static void main(String argv[]) { 
    Bground b = new Bground(1); 
    Bground b2 = new Bground(2); 

    ExecutorService es = Executors.newFixedThreadPool(2); 
    es.submit(b); 
    es.submit(b2); 
    synchronized (es) { 
     es.notifyAll(); 
    } 

    try { 
     for (int i = 0; i < 5; i++) { 
      System.out.println("In main thread" + i); 
      Thread.sleep(1); 
     } 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
} 

}