多线程的强制执行
当需要一个线程强制执行时可以使用join()方法.
实例:
public class Test11 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("vip线程来了"+i);
}
}
public static void main(String[] args) throws InterruptedException {
Test11 test = new Test11();
Thread th=new Thread(test);
for (int i = 0; i < 500;i++) {
System.out.println("main"+i);
if (i==200){
th.join();//强制执行
}
}
}
}
线程优先级
线程中不能设置cpu调用的先后顺序,但是可以设置线程的优先级Thread类提供了setPriority()来设置线程的优先级.
Thread类的三个优先级参数常量:
注意事项:
守护线程
线程分为用户线程和守护线程,一般默认为用户线程如,main()方法就是用户线程,他有个垃圾回收的GC守护线程,Thread类中提供setDaemon(boolean on)方法可设置守护线程.
实例:
public class Test14 {
//守护线程
private static class Test1 implements Runnable{
@Override
public void run() {
int i=0;
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("默默受守护中"+i++);
}
}
}
//用户线程
private static class Test2 implements Runnable{
@Override
public void run() {
for (int i = 0; i <= 36000; i++) {
System.out.println("用户出生第"+i);
}
}
}
public static void main(String[] args) {
Thread th=new Thread(new Test1());
//设置线程为守护线程
th.setDaemon(true);
//启动守护线程
th.start();
//用户线程
Thread th1=new Thread(new Test2());
th1.start();
}
}