//后台线程与setDaemon()方法和线程的强制运行
package 多线程;
class Thread_Daemo_and_Join implements Runnable
{
public void run()
{
// while(true)
// {
// System.out.println(Thread.currentThread().getName()+"is running");
// }
int i = 0;
for(int x = 0 ; x < 10 ; x++)
{
System.out.println(Thread.currentThread().getName()+"--->>"+i++);
}
}
}
public class setDaemon {
public static void main(String[] args) {
// Thread_Daemo_and_Join td = new Thread_Daemo_and_Join();
// Thread t1 = new Thread(td);
// t1.setDaemon(true);//设置为后台线程
// t1.start();
Thread_Daemo_and_Join tj = new Thread_Daemo_and_Join();
Thread t2 = new Thread(tj);
t2.start();
int i = 0 ;
for(int x = 0 ; x < 10 ; x++)
{
if(x==5)
{
try
{
// t2.join(100);
// t2.join(100, 2);
t2.join();//强制运行完pp线程后,再运行main线程
}
catch(Exception e)
{
System.out.println(e.getStackTrace());
}
}
System.out.println("main Thread "+i++);
}
}
}
//后台线程与setDaemon()方法
//只要还有一个前台线程在运行,这个线程就不会结束,如果一个进程中只有后台线程在运行,这个进程就会结束。
//如果某个线程对象在启动之前调用了setDaemon(true)方法,这个线程就变成了自动线程。
//这里虽然建立了一个无线循环的线程,但因为它是后台线程,因此整个进程在主线程结束时就随之终止运行了。
//线程的强制运行
//t2线程并入到了main线程中,t2线程不执行完,main线程中的代码就要不断等待,
//还有jion(long millis)、jion(long millis,int nanos)指定两个线程的合并指定时间后再分离


