线程

线程方法

线程的停止(建议)

线程的休眠

线程礼让


A和B 两个线程,当CPU执行B的时候,B进行礼让,那么就离开cpu,这个时候B就变为就绪状态,CPU就重新 在A线程和B线程之间进行选择,有可能还是让B线程执行,这个时候就没有礼让成功。

join

相当于插队

线程的优先级


利用代码设置线程的优先级 和 获取线程的优先级

public class Priority {
   

    public static void main(String[] args) {
   

        System.out.println(Thread.currentThread().getName()+"===="+Thread.currentThread().getPriority());
        mytest mytest = new mytest();

        Thread thread = new Thread(mytest);
        Thread thread1 = new Thread(mytest);
        Thread thread2 = new Thread(mytest);
        Thread thread3 = new Thread(mytest);
        Thread thread4 = new Thread(mytest);
        Thread thread5 = new Thread(mytest);


        thread.start();
        设置线程的优先级
        thread1.setPriority(2);
        thread1.start();
        thread2.setPriority(8);
        thread2.start();
        thread3.setPriority(9);
        thread3.start();
        thread4.setPriority(5);
        thread4.start();
        thread5.setPriority(1);
        thread5.start();



    }
}

class mytest  implements Runnable{
   


    @Override
    public void run() {
   
        System.out.println(Thread.currentThread().getName()+"===="+Thread.currentThread().getPriority());
    }
}

守护线程


main函数就是用户线程
gc 垃圾回收机制 就是 守护线程

当我们执行一段程序,里面有很多的线程,其中一个线程是守护线程,那么当其他线程执行完毕,这个守护线程就关闭了,虚拟机是不管守护线程是否关闭的

public class TestDeamon {
   
    public static void main(String[] args) {
   
        god god = new god();
        yhxc yhxc = new yhxc();

        Thread thread = new Thread(god);
        thread.setDaemon(true);
        Thread thread1 = new Thread(yhxc);
        thread.start();
        thread1.start();
    }
}


class god implements Runnable{
   
    @Override
    public void run() {
   
        while (true){
   
            System.out.println("我是守护线程");
        }
    }
}

class yhxc implements Runnable{
   
    @Override
    public void run() {
   
       for(int i=0;i<100;i++){
   
            System.out.println("我是用户线程");
        }
        System.out.println("我结束了");
    }
}

思路:

我们参加一个 用户线程,一个守护线程,如果一个线程要变为守护线程,那么必须手动设置为true。当我们用户线程走完,整个就结束了,虚拟机是不管守护线程是否走完的。

守护线程不用管