线程休眠:
使用Thread.sleep(long millis)可以使线程休眠,也就是将正在执行的线程暂停,将CPU让给其他线程去执行。
实例:
public class Example06 {
public static void main(String[] args) {
SleepThread sleepThread = new SleepThread();
new Thread(sleepThread,"线程A").start();
for (int i = 0; i <= 5; i++) {
if (i == 5){
//i=5时,休眠2秒
try {
Thread.sleep(2000);
}catch (Exception e){
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "输出了" + i);
}
}
}
//SleepThread实现Runnable接口
class SleepThread implements Runnable {
public void run() {
for (int i = 0; i <= 5; i++) {
try {
if (i == 5) {
//i=5时,休眠2秒
Thread.sleep(2000);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "输出了" + i);
}
}
}
运行结果:
线程让步:
线程让步可以通过yield()方法来实现,该方法和sleep()方法相似,都可以让正在运行的线程暂停。区别在于yield()方法不会阻塞该线程,只会将线程转换为就绪状态,让系统调度器从新调度一次。当线程调用yield()方法之后,只有与当前线程优先级相同或者更高的线程才会获得执行的机会。
实例:
public class Example07 {
public static void main(String[] args) {
yieldThread yieldThread1 = new yieldThread();//创建实例
new Thread(yieldThread1,"线程A").start();//启动线程
yieldThread yieldThread2 = new yieldThread();//创建实例
new Thread(yieldThread2,"线程B").start();//启动线程
}
}
class yieldThread implements Runnable{
public void run() {
for (int i = 0; i <= 5; i++ ){
System.out.println(Thread.currentThread().getName() + "---" + i);
if (i == 4){
System.out.print("线程让步了:");
Thread.yield();//线程执行到这会让步
}
}
}
}
运行结果:
线程插队:
在一个线程中调用其它线程的join()方法时,调用的线程将会阻塞,直到被加入的线程执行完之后它才会运行。
实例:
public class Example08 {
public static void main(String[] args) throws Exception {
Thread a = new Thread(new JoinThread(), "线程A");
a.start();
for (int i = 0; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + "输出" + i);
if (i == 2){
a.join();//调用join()方法
}
Thread.sleep(1000);//休眠1秒中
}
}
}
class JoinThread implements Runnable {
public void run() {
for (int i = 0; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + "输出" + i);
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
运行结果:
加油吧!!!