面试1:现有T1,T2,T3三个线程,如何保证T1完执行T2,T2完执行T3?
package com.ruge.rugesecurity.controller.index;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
public class ThreadTest {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new Thread1("==="));
thread1.start();
thread1.join();
Thread thread2 = new Thread(new Thread1("======"));
thread2.join();
thread2.start();
Thread thread3 = new Thread(new Thread1("========="));
thread3.start();
thread3.join();
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
class Thread1 implements Runnable {
private String name;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("运动的用户是" + name + i);
}
}
}
class Thread2 implements Runnable {
private String name;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("运行的用户是" + name + i);
}
}
}
class Thread3 implements Runnable {
private String name;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("唱歌的用户是" + name + i);
}
}
}
面试2:wait和sleep的区别
sleep不会释放对象锁,wait会放弃对象锁
sleep时间到自动进入就绪状态
wait需要等待notify唤醒才会进入就绪状态