sleep方法:
Thread.sleep(5) 单位是毫秒,意思是把当前
线程休眠5毫秒.
class="java">public class Test {
public static void main(String[] args) {
Thread myThread = new Thread(new MyThread(),"myThread");
myThread.start();
for (int i = 0; i < 1000; i++) {
if (i % 2 == 0) {
// 主线程休眠5毫秒
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("test" + i);
}
}
}
class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i <= 1000; i++) {
System.out.println(i);
}
}
}
yield 方法:
该方法是让出当前线程,让其他线程执行
public class Test {
public static void main(String[] args) {
MyThread myThread1 = new MyThread("t1");
MyThread myThread2 = new MyThread("t2");
myThread1.start();
myThread2.start();
}
}
class MyThread extends Thread {
public MyThread(String arg){
super(arg);
}
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
System.out.println(getName()+":"+i);
if (i % 10 == 0) {
// 注意:一定是Thread.yield(), 不要直接调用yield()方法
// 线程让出一段时间,等到cpu执行该线程时在执行
Thread.yield();
}
}
}
}