gpt4 book ai didi

java - 线程行为:Java Beginner

转载 作者:行者123 更新时间:2023-12-01 19:06:19 26 4
gpt4 key购买 nike

我尝试编写一个使用线程的程序,但无法理解 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();
}
}
}

操作:

c:\Program Files\Java\jdk1.6.0_23\bin>java Bground

In main thread0
inside runfirst thread
inside runfirst thread
In child thread0
In child thread1
In child thread2
In main thread1
In child thread3
In child thread0
In child thread1
In child thread2
In child thread3
In child thread4
In main thread2
In child thread4
In main thread3
In main thread4

最佳答案

您期望打印出什么内容:

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

您无法在此处获取当前线程的名称,但您始终会获取 t-Thread 的名称。要修复 - 获取当前线程并对其调用getName()

关于java - 线程行为:Java Beginner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9952048/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com