- 线程控制的三个方法
- 1线程等待
- 2.等待到线程死亡
- 3.把线程设置为守护线程
我们讲解 线程控制的三个方法
static void sleep(long millionTime) 暂停线程的运行 单位为毫秒
void join() ; 等待这个线程死亡
void setDeamon(boolean on) 将此线程标记为守护线程,当所有线程都是死亡线程的时候 JVM退出
public class demo01 {
//第一个我们来讲解sleep方法
public static void main(String[] args) {
//创建三个线程
Mythread mythread1 = new Mythread();
Mythread mythread2 = new Mythread();
Mythread mythread3 = new Mythread();
//设置线程的名字
mythread1.setName("one");
mythread2.setName("two");
mythread3.setName("three");
//直接启动线程
mythread1.start();
mythread2.start();
mythread3.start();
}
//创建一个线程内部类
static class Mythread extends Thread{
@Override
public void run() {
for (int i = 0 ; i< 100 ;i++){
System.out.println(getName()+i);
//休眠一秒
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//加入了休眠线程就相当于一秒输出一次
}
}
}
}
2.等待到线程死亡
public class demo02_ThreadJoin {
public static void main(String[] args) throws InterruptedException {
//创建三个线程
Mythread mythread1 = new Mythread();
Mythread mythread2 = new Mythread();
Mythread mythread3 = new Mythread();
//设置线程的名字
mythread1.setName("皇上");
mythread2.setName("太子一");
mythread3.setName("太子二");
//直接启动线程
mythread1.start();
mythread1.join();//等到皇上驾崩
mythread2.start();
mythread3.start();
}
public static class Mythread extends Thread{
@Override
public void run() {
for (int i = 0 ; i< 100 ; i++){
System.out.println(getName()+i);
}
}
}
3.把线程设置为守护线程
public class demo03_ThreadserDeamon {
public static void main(String[] args) {
//创建三个线程
Mythread mythread1 = new Mythread();
Mythread mythread2 = new Mythread();
//获得当前的线程就是主线程
Thread.currentThread().setName("刘备");
System.out.println("主线程优先级:"+Thread.currentThread().getPriority());
//设置线程的名字
mythread1.setName("关羽");
mythread2.setName("张飞");
//这时候一共有三个线程都在执行for循环
for (int i = 0 ; i< 30 ; i++){
System.out.println(Thread.currentThread().getName()+i);
}
//为关羽和张飞这只守护线程
mythread1.setDaemon(true);
mythread2.setDaemon(true);
//直接启动线程
mythread1.start();
mythread2.start();
}
public static class Mythread extends Thread{
@Override
public void run() {
for (int i = 0 ; i< 100 ; i++){
System.out.println(getName()+i);
}
}
}
}



