线程常用方法
守护线程、用户线程
线程默认的都是用户线程,我们需要设置thread.setDaemon(true)来改为守护线程;
守护线程,虚拟机不会监测它,等别的线程都跑完了,守护线程会自动停止;
public static void main(String[] args) {
Teacher teacher = new Teacher();
Thread thread = new Thread(teacher);
// TODO 老师设置为守护线程
thread.setDaemon(true);
thread.start();
Student student = new Student();
new Thread(student).start();
}
static class Student implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("学生到家了!");
}
System.out.println("------------------------------------");
}
}
static class Teacher implements Runnable{
@Override
public void run() {
// 死循环,但是因为是守护线程,虚拟机不会监测它,等别的线程都跑完了,守护线程会自动停止;
while(true){
System.out.println("老师送学生回家!");
}
}
}
线程礼让yield
Thread.yield();
礼让不一定成功,只是优先级的变化,还是看cpu的调度;
线程插队join
Thread.join();
少用,会导致阻塞,了解即可;
线程状态
Thread.getState();
优先级priority
getPriority(),setPriority(int XXX)
先设置优先级,在启动,优先级只有1~10,默认是5;也不一定优先级高的肯定会跑,看cpu心情;