sleep,join,interrupt,yield
sleep
Thread类的一个静态方法,作用是让当前线程阻塞一定时间(以毫秒为单位),假如有锁的话,sleep是不释放锁的(wait,join释放锁)。
源码:
public static native void sleep(long millis) throws InterruptedException;
例子:
public class Test {
public static void main(String[] args) {
try {
System.out.println("before sleep");
Thread.sleep(5000);
System.out.println("after sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
interrupt
中断线程(实际上interrupt不会中断线程,需要跟isInterrupt函数配合使用),通过return或者抛InterruptedException停止线程
ublic class Test {
public static void main(String[] args) throws InterruptedException {
ThreadA threadA=new ThreadA();
Thread thread=new Thread(threadA);
thread.start();
Thread.sleep(2000);
thread.interrupt();
Thread.sleep(2000);
for(int i=0;;i++){
Thread.sleep(2000);
System.out.println("finish"+i);
}
}
}
class ThreadA implements Runnable{
public void run() {
try {
int count=0;
while(!Thread.currentThread().isInterrupted()){
System.out.println(count++);
}
//可以通过return停止线程
// return;
//可以通过抛InterruptedException停止线程
throw new InterruptedException();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
join
作用是让两个线程同步。例如:有A,B两个线程,如果在B中调用了A.join()的话,则表示A线程执行完了才开始执行B线程
例如:上面interrupt例子,假如我需要把子线程执行完才最后输出finish,那么可以用join方法。
改为:
public class Test {
public static void main(String[] args) throws InterruptedException {
ThreadA threadA=new ThreadA();
Thread thread=new Thread(threadA);
thread.start();
Thread.sleep(2000);
thread.interrupt();
thread.join();
for(int i=0;;i++){
Thread.sleep(2000);
System.out.println("finish"+i);
}
}
}
class ThreadA implements Runnable{
public void run() {
try {
int count=0;
while(!Thread.currentThread().isInterrupted()){
System.out.println(count++);
}
Thread.sleep(3000);
//可以通过return停止线程
return;
//可以通过抛InterruptedException停止线程
// throw new InterruptedException();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
yield
作用是暂停当前正在执行的线程,并执行其他线程。
yield()让当前正在运行的线程回到可运行状态,以允许具有相同优先级的其他线程获得运行的机会。因此,使用yield()的目的是让具有相同优先级的线程之间能够适当的轮换执行。但是,实际中无法保证yield()达到让步的目的,因为,让步的线程可能被线程调度程序再次选中。
结论:大多数情况下,yield()将导致线程从运行状态转到可运行状态,但有可能没有效果。
public class Test {
public static void main(String[] args) throws InterruptedException {
new ThreadA("A").start();
new ThreadA("B").start();
}
}
class ThreadA extends Thread{
private String name;
ThreadA(String name ){
this.name=name;
}
public void run() {
System.out.println("Thread-"+name+"start");
for (int i = 1; i <= 50; i++) {
System.out.println("" + name + "-----" + i);
// 当i为30时,该线程就会把CPU时间让掉,让其他或者自己的线程执行(也就是谁先抢到谁执行)
if (i == 30) {
this.yield();
}
}
System.out.println("Thread-"+name+"end");
}
}
结果:(一种可能)B先到30,yield,A抢到cpu时间然后执行了一段时间
A-----16
B-----29
B-----30
A-----17
A-----18
A-----19
A-----20
A-----21
A-----22
A-----23
A-----24
A-----25
A-----26
A-----27