【问题标题】:Thread Behavior:Java Beginner线程行为:Java初学者
【发布时间】:2012-04-14 16:10:53
【问题描述】:

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

谁能向我解释一下这种行为?谢谢

我的代码:

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

在主线程0
在 runfirst 线程内
在 runfirst 线程内
在子线程0
在子线程1
在子线程2
在主线程1
在子线程3
在子线程0
在子线程1
在子线程2
在子线程3
在子线程4
在主线程2
在子线程4
在主线程3
在主线程4

【问题讨论】:

  • 只是让你知道:每次你这样格式化你的代码,上帝杀死一只小猫。
  • 考虑让每个线程都有一个Thread.sleep(1000)。参数以毫秒为单位。

标签: java multithreading


【解决方案1】:

您期望打印出来的内容:

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

您不会在这里获得当前线程的名称,而是始终获得 t-Thread 的名称。修复——获取当前线程并在其上调用getName()

【讨论】:

  • 是的,对不起那是愚蠢的..我证明了一个初学者,dint i ?? :)
【解决方案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();
    }
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    • 2010-10-06
    • 2014-10-03
    • 1970-01-01
    • 2011-08-13
    相关资源
    最近更新 更多