各位大虾们
现在我已经创建了以个线程A。
我还想用这个线程A创建另外的一个线程b。
可以这样理解:线程b是由线程A创建的。
这样的话,线程b可以创建吗?
有没有代码可以参考的?[color=darkred][/color]
各位大虾们
现在我已经创建了以个线程A。
我还想用这个线程A创建另外的一个线程b。
可以这样理解:线程b是由线程A创建的。
这样的话,线程b可以创建吗?
有没有代码可以参考的?[color=darkred][/color]
首先,线程可以继续创建线程.
给你看个例子:
[code="java"]
public class SimpleThreads {
// Display a message, preceded by the name of the current thread
public static void threadMessage(String message) {
String threadName = Thread.currentThread().getName();
System.out.format("%s: %s%n", threadName, message);
}
public static void main(String args[]) throws InterruptedException {
Thread t = new Thread(new TestThread());
t.start();
}
}
class TestThread implements Runnable {
private static int depth = 0;
@Override
public void run() {
SimpleThreads.threadMessage("Thread Start");
SimpleThreads.threadMessage("Depth= " + depth);
if (depth < 5) {
depth++;
new Thread(new TestThread()).start();
}
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SimpleThreads.threadMessage("Thread END");
}
}
[/code]
例子里的TestTread就通过自己反复创建子线程.
应该看的比较清楚了.输出是:
[quote]Thread-0: Thread Start
Thread-0: Depth= 0
Thread-1: Thread Start
Thread-1: Depth= 1
Thread-2: Thread Start
Thread-2: Depth= 2
Thread-3: Thread Start
Thread-3: Depth= 3
Thread-4: Thread Start
Thread-4: Depth= 4
Thread-5: Thread Start
Thread-5: Depth= 5
Thread-0: Thread END
Thread-1: Thread END
Thread-2: Thread END
Thread-3: Thread END
Thread-4: Thread END
Thread-5: Thread END
[/quote]