天天看點

線程的休眠

所謂的線程休眠指的就是讓線程的執行速度稍微的變慢一點。

休眠的方法:

public static void sleep(long millis,int nanos)throws InterruptedException

觀察休眠的特點:

class MyThread implements Runnable{

	@Override
	public void run() {
		for(int x = 0 ; x < 10000 ; x ++){
			try {
				Thread.sleep(1000);//休眠1秒
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + ", x = " + x );
		}
	}
}
public class Demo{
	public static void main (String [] args){
		MyThread mt = new MyThread() ;
		new Thread(mt,"線程A").start();
	}
}
           

預設情況下,在休眠的時候如果設定了多個線程對象,那麼所有的線程對象将一起進入到run()方法(所謂的一起進入實際上是因為先後順序太短了,但實際上有差別。)

正因為這一點細微的差别,有可能造成我們資料的錯誤!