Java多线程文章目录
目录
设置优先级
join方法
sleep方法
sleep()实现秒表功能
常见面试题
setDaemon方法
设置优先级
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类中的方法
线程调用sleep()方法后,短暂暂停线程的运行,当前线程不会释放它的资源
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);
}
}
}



