目录
设置优先级
- 同优先级别的线程,采取的策略就是先到先服务,使用时间片策略
- 如果优先级别高,被CPU调度的概率就高(是概率高,不是一定)
- 级别:1-10,默认级别是5
Thread类(java.lang包下)
public class TestThread01 extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}
class TestThread02 extends Thread {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(i);
}
}
}
class TestThread {
// Main方法:
public static void main(String[] args) {
// 创建两个子线程,让这两个子线程争抢资源
TestThread01 testThread01 = new TestThread01();
testThread01.setPriority(10);
testThread01.start();
TestThread02 testThread02 = new TestThread02();
testThread02.setPriority(1);
testThread02.start();
}
}
join方法
join方法:当一个线程调用了join方法,这个线程就会先被执行,它执行结束以后才可以去执行其余的线程。
注:必须先start(),再join()才有效
sleep方法
sleep():人为制造阻塞状态
运行后控制台显示运行完成,但是数字会在3秒后输出在控制台
sleep()实现秒表功能
public class Test01 {
// Main方法:
public static void main(String[] args) {
// 定义一个时间格式
DateFormat df = new SimpleDateFormat("HH:mm:ss");
while(true){
// 获取当前时间:
Date d = new Date();
// 按照上面定义的格式将Date类型转为指定格式的字符串:
System.out.println(df.format(d));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
常见面试题
sleep()、wait()和yield()的区别
- 区别
- sleep()和yield()是Thread类中的方法
- wait()是Object类中的方法
- 也就是说,在java中,所有的类都有wait()方法,而只有继承了Thread类的才有sleep()和yield()方法
- sleep()和wait()的区别
- 线程调用sleep()方法后,短暂暂停线程的运行,当前线程不会释放它的资源
- wait()方法用于线程间的通信,线程调用wait()方法后,当前线程会释放它的资源
- sleep()和yield()的区别
- sleep()是被动的(被写代码的,人为进入阻塞状态)
- yield()是主动的,当前线程已经执行的差不多了,告诉CPU“可以把我的资源让给比我线程优先级更高的线程或者跟我同级的线程去执行”,如果没有这样的线程,那么当前线程继续执行,如果有那么当前线程进入就绪状态
setDaemon方法
设置伴随线程:将子线程设置为主线程的伴随线程,主线程停止的时候,子线程也不要继续执行了
public class TestThread02 extends Thread {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("子线程---" + i);
}
}
// Main方法:
public static void main(String[] args) {
// 创建并启动子线程
TestThread02 testThread02 = new TestThread02();
testThread02.setDaemon(true);
testThread02.start();
// 主线程输出1-10数字
for (int i = 0; i < 10; i++) {
System.out.println("主线程---" + i);
}
}
}