Java中的多线程
这是我的密码Java中的多线程,java,multithreading,Java,Multithreading,这是我的密码 public class ThreadLearn{ private static class Check implements Runnable{ public void run(){ System.out.printf("\nInCheck %s", Thread.currentThread().getName()); } } public static void main(String[] args){ Thread t; in
public class ThreadLearn{
private static class Check implements Runnable{
public void run(){
System.out.printf("\nInCheck %s", Thread.currentThread().getName());
}
}
public static void main(String[] args){
Thread t;
int i=0;
while(i<2){
t = new Thread(new GetData());
t.start();
System.out.printf("\n%s: ", t.getName());
i++;
}
}
}
我有两个问题:
t.start()
完成,它会等待run()
执行,然后创建第二个线程吗?如果我想做以下事情呢
while(必需)
新线程().start()t.start()
完成,它会等待run()
执行,然后创建第二个线程吗
不,不会等的。新线程的
run();在不同的运行中,可能会有其他顺序。当线程启动时,它就启动了。因此,这两个System.out几乎同时执行,导致它们有时会改变顺序
例如:
---- thread-0 prints out
Main thread |--- Prints out ----------- Prints out
|Thread-1 started, prints out
正如您所看到的,分支将与主代码在几乎相同的时间运行,导致它们在实际打印出来的时间之间波动我认为您应该修改您的代码段!这个相关的问题没什么意义,所以它已经满足了我的第2个问题,对吧?线程被创建并独立运行,无需等待任何操作。我可以把实现放在run方法中,它们将继续并行执行?@Kraken是的,这就是线程的全部意义,你可以让多个东西并行运行,相互独立。假设我创建了一个新线程t
,并且我的类Check
或我希望该线程运行的任何其他类中有一个函数,那么既然t.method()
不起作用,我该怎么做呢?如何做到这一点?因此,如果我想产生多个线程并让它们并行工作,我可以使用与上面相同的方法,将实现放在run()
方法中,对吗?
---- thread-0 prints out
Main thread |--- Prints out ----------- Prints out
|Thread-1 started, prints out