1.Thread类的常用方法
(1)sleep()
导致当前正在执行的县城休眠(暂时停止执行)指定的毫秒数,具体取决于系统计时器和调度程序的精度和准确性。
package com.thread;
class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 1; i < 10; i++) {
System.out.println(i);
try {
Thread.sleep(2000);//线程休眠2秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Demo01{
public static void main(String[] args) {
MyRunnable myRunable=new MyRunnable();
Thread thread1=new Thread(myRunable);
thread1.start();
}
}
输出结果:间隔两秒输出下一个值。
(2)yield()
线程让步是通过Thread.yield()实现,让当前进程停下换成就绪状态,让系统的调度器重新调度,但yield()方法不会阻塞当前线程,它与其他线程是相对公平的,等待线程再一次调度,有可能调度的是其他线程也可能还调度的是自己。
package com.thread;
class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 1; i <100; i++) {
System.out.println(Thread.currentThread().getName()+i);
Thread.yield();//线程让步
}
}
}
public class Demo01{
public static void main(String[] args) {
MyRunnable myRunable=new MyRunnable();
Thread thread1=new Thread(myRunable);
thread1.start();
for (int i = 1; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+i);
}
}
}
输出结果:
由结果可看出,线程让步之后还可能调度自己。
(3)join()
线程插队,阻塞当前线程,让调用了join的这个方法的这个线程先执行,等这个线程执行完毕,才来执行其他线程。
package com.thread;
class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 1; i <10; i++) {
System.out.println(Thread.currentThread().getName()+i);
}
}
}
public class Demo01{
public static void main(String[] args) throws InterruptedException {
MyRunnable myRunable=new MyRunnable();
Thread thread1=new Thread(myRunable);
thread1.start();
for (int i = 1; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+i);
if(i==5) {
thread1.join();
}
}
}
}
(4)interrupted()
中断此线程,默认为false。
package com.thread;
import java.io.IOException;
class MyRunnable implements Runnable{
@Override
public void run() {
while(!Thread.interrupted()){
System.out.println(Thread.currentThread().getName()+"线程执行中");
}
}
}
public class Demo01{
public static void main(String[] args) throws InterruptedException, IOException {
MyRunnable myRunable=new MyRunnable();
Thread thread1=new Thread(myRunable);
thread1.start();
System.in.read();//键盘录入一个值
thread1.interrupt();//打断当前线程
}
}
输出结果,键盘录入值之前一直打印,当录入值之后线程被打断,不再输出值,线程终止。