JAVA 静态块 线程问题

来源:百度知道 编辑:UC知道 时间:2024/07/06 21:39:32
public class HelloWorld {
private static boolean initialized = false;
static Thread t = new Thread(new Runnable() {
public void run() {
System.out.print(initialized); //label
System.out.print("Hello ");
initialized = true;

}
});
static{
t.start();
try{
t.join();
}catch (InterruptedException e){
throw new AssertionError(e);
}

}

public static void main(String[] args){
System.out.println(" world!");
}

}
谁能解释下这段代码的执行流程?静态块是在MAIN()之前就运行了吧??为甚吗去掉Label处代码可以打印出Hello,而添上Label处代码就什么都不显示 一直在等待状态? 谢谢
越详细 越好!!~!

静态块是在类加载的时候就执行的
所以先执行
static{
t.start();//启动txianc
try{
t.join();//此时在 线程t执行完之后在继续执行
//也就是自己阻塞了自己
}catch (InterruptedException e){
throw new AssertionError(e);
}

在执行main方法

程序改为下面的应该就是你想要的
可以参考下

public class HelloWorld {
private static boolean initialized = false;
static Thread t = new Thread(new Runnable() {
public void run() {
System.out.print(initialized); //label
System.out.print("Hello ");
initialized = true;

}
});
static{
t.start();
}

public static void main(String[] args){
try{
t.join();
}catch (InterruptedException e){
throw new AssertionError(e);
}