线程的sleep、join、yield、wait方法

sleep方法:可以调用Thread的静态方法 public static void sleep(long millis) throws InterruptedException 使得当前线程休眠(暂停执行millis毫秒)、由于是静态方法,sleep可以由类名直接调用:Thread.sleep()
wait 与 sleep区别:wait时别的线程可以访问锁定对象——调用wait方法时必需锁定该对象、sleep时别的线程也不可以访问锁定对象
import java.util.*;

public class TestInterrupt {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 继承与Thread类,可以直接调用start()启动线程
try {
Thread.sleep(10000); // 在主线程中调用sleep,主线程则sleep
} catch (InterruptedException e) {
}
thread.shutDown(); // 结束子线程
// thread.interrupt(); //调用interrupt()会抛异常
}
}

class MyThread extends Thread {
boolean flag = true; // 控制线程的结束标志

public void run() {
while (flag) {
System.out.println("===" + new Date() + "===");
try {
sleep(1000); //
} catch (InterruptedException e) { // 本线程抛异常则结束线程
return;
}
}
}

public void shutDown() {
flag = false;
}
}

join方法:合并某个线程

public class TestJoin {
public static void main(String[] args) {
MyThread2 t1 = new MyThread2("abcde"); // 给t1取个名字
t1.start(); // t1产生一个分支线程
try {
t1.join(); // 合并线程,则只有一个线程,按顺序执行
} catch (InterruptedException e) {
}

for (int i = 1; i <= 10; i++) {
System.out.println("i am main thread");
}
}
}

class MyThread2 extends Thread {
MyThread2(String s) {
super(s); // 调用父类构造方法,设置名字
}

public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("i am " + getName());
try {
sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
}

yield方法:让出CPU,给其他线程执行的机会

public class TestYield {
public static void main(String[] args) {
MyThread3 t1 = new MyThread3("t1");// 同一线程new两对象,共3条线程
MyThread3 t2 = new MyThread3("t2");
t1.start();
t2.start();
}
}

class MyThread3 extends Thread {
MyThread3(String s) {
super(s);
}

public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println(getName() + ": " + i);
if (i % 10 == 0) { // 每到10的倍数则切换线程
yield();
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值