Th()方法使运行它的线程进入Hibernate 状态. 下面代码中的thread.sleep()语句将由主线程运行,下面代码中的‘线程’是用户定义的线程.为什么在调用用户定义的线程的引用时主线程处于Hibernate 状态.
public class ThreadDemo {
public static Thread t1 = null;
public static Thread t2 = null;
public static void main(String[] args) throws InterruptedException{
System.out.println("start of main function, Thread : "+Thread.currentThread().getName());
t1 = Thread.currentThread(); //main thread
MyThread thread = new MyThread();
t2 = thread;
thread.start();
System.out.println("Before sleep in main method : "+System.currentTimeMillis());
thread.sleep(1000);
System.out.println("After sleep in main method : "+System.currentTimeMillis());
System.out.println("In main method, Thread : "+t1.getName()+" ,In state: "+t1.getState());
System.out.println("In main method, Thread : "+t2.getName()+" ,In state: "+t2.getState());
System.out.println("Is thread, "+thread.getName() + " alive : "+ thread.isAlive());
System.out.println("end of main function, Thread : "+Thread.currentThread().getName());
}
public static class MyThread extends Thread{
int sum = 0;
@Override
public void run() {
System.out.println("In run method, Thread : "+t1.getName()+" ,In state: "+t1.getState());
System.out.println("In run method, Thread : "+t2.getName()+" ,In state: "+t2.getState());
System.out.println("start of run method, Thread : "+Thread.currentThread().getName());
for(int i=0; i<10000; i++){
sum += i;
}
try{
Thread.sleep(10000);
System.out.println("After sleep in run method : "+System.currentTimeMillis());
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("end of run method, "+ Thread.currentThread().getName() +", returns : "+sum);
}
}
}
输出:
start of main function, Thread : main
Before sleep in main method : 1701105524066
In run method, Thread : main ,In state: TIMED_WAITING
In run method, Thread : Thread-0 ,In state: RUNNABLE
start of run method, Thread : Thread-0
After sleep in main method : 1701105525070
In main method, Thread : main ,In state: RUNNABLE
In main method, Thread : Thread-0 ,In state: TIMED_WAITING
Is thread, Thread-0 alive : true
end of main function, Thread : main
After sleep in run method : 1701105534071
end of run method, Thread-0, returns : 49995000
我不明白在用户定义的线程的引用上调用主线程时,主线程是如何Hibernate 的.