sleep 方法
public class Demo01Sleep {
public static void main(String[] args) {
//模拟秒表
for (int i = 1; i <=60 ; i++) {
System.out.println(i);
//使用Thread类的sleep方法让程序睡眠1秒钟
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
yield方法
线程礼让,使当前线程取消cpu的执行权,重新进入等待队列(有可能重新抢夺到cpu执行权)
static void testYield() {
new Thread(()->{
for(int i=0; i<100; i++) {
System.out.println("A" + i);
if(i%10 == 0) {
Thread.yield();
}
}
}).start();
new Thread(()->{
for(int i=0; i<100; i++) {
System.out.println("------------B" + i);
if(i%10 == 0) {
Thread.yield();
}
}
}).start();
}
join方法
线程加入,使一个线程加入到另一个线程中,需要等待加入的线程执行结束之后才能执行当前线程
static void testJoin() {
Thread t1 = new Thread(()->{
for(int i=0; i<100; i++) {
System.out.println("A" + i);
try {
Thread.sleep(500);
//TimeUnit.Milliseconds.sleep(500)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(()->{
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i=0; i<100; i++) {
System.out.println("A" + i);
try {
Thread.sleep(500);
//TimeUnit.Milliseconds.sleep(500)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
getState获取线程状态
public class T04_ThreadState {
static class MyThread extends Thread {
@Override
public void run() {
System.out.println(this.getState());
for(int i=0; i<10; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
}
}
}
public static void main(String[] args) {
Thread t = new MyThread();
System.out.println(t.getState());
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.getState());
}
}
getPrioty(),setPrioty()
获取和修改线程的优先级
守护线程
import java.util.concurrent.TimeUnit;
/**
* @author name
* @date 2020/7/22
* 测试守护线程
* 当JVM中所有的线程都是守护线程的时候,JVM就可以退出了;
* 如果还有一个或以上的非守护线程则不会退出。(以上是针对正常退出,调用System.exit则必定会退出)
* 最常见的就是jc线程
*/
public class TestDemo {
public static void main(String[] args) {
//设置一个钩子线程,在JVM退出时输出日志
Runtime.getRuntime().addShutdownHook(new Thread(() -> System.out.println("jvm exit")));
//新建一个非守护线程
Thread thread = new Thread(() -> {
while (true) {
try {
TimeUnit.SECONDS.sleep(1);
System.out.println("i am running");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
//设置为守护线程
thread.setDaemon(true);
thread.start();
System.out.println("主线程结束");
}
}