初识JAVA---线程的控制Daemon(9)

当new了一个thread线程  然后start  它就是就绪状态  具体那一瞬间分配到cpu执行,是由操作系统调度

调度过程中有运行状态,可能有导致阻塞的时间  比如等待IO操作的时候,这个时候就是阻塞状态,

这个过程可以有一些控制

对线程的基本控制

start()启动线程      默认线程结束是,run中的方法执行完了就结束了

如果是无线循环的,常用的是标记变量来结束相应的循环来结束

暂时阻止线程的执行  try{Thread.sleep(1000);}catch(InterruptedException e){} 

设定线程的优先级  setPriority(int priority) 方法  MIN_PRIORITY MAX_PRIORITY NORM_PRIORITY

线程有两种 

普通线程

守护线程 后台线程 Daemon  

如果普通线程结束了   后台线程自动终止  垃圾回收机制是后台线程

import java.util.*;
public class TestThreadDaemon{
	public static void main(String args[]) {
		Thread t=new MyThread();
		t.setDaemon(true);
		t.start();
		
		System.out.println("Main--"+new Date());
		try {Thread.sleep(600);}
		catch(InterruptedException ex) {}
		System.out.println("Main End");
	}//main方法所在的就是主线程
}
class MyThread extends Thread{
	public void run() {
		for(int i=0;i<10;i++) {
			System.out.println(i+"--"+new Date());
			try {Thread.sleep(100);}
			catch(InterruptedException ex) {}
		}
	}
}

输出

0--Tue Dec 24 15:42:11 CST 2019
Main--Tue Dec 24 15:42:11 CST 2019
1--Tue Dec 24 15:42:12 CST 2019
2--Tue Dec 24 15:42:12 CST 2019
3--Tue Dec 24 15:42:12 CST 2019
4--Tue Dec 24 15:42:12 CST 2019
5--Tue Dec 24 15:42:12 CST 2019
Main End

看程序  它并不会在run中执行完10次  因为上面这个线程是daemon的,它在main函数中是主线程,当main执行完毕之后,会垃圾回收,所以它在run中挂起来的任务也会小时, 我们看到执行了6次是因为  阻塞了600ms 而 run中的线程等待100ms刚好6次

发布了103 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_39653453/article/details/103677879