Java Thread sleepとwaitの違い
2172 ワード
私たちはJavaスレッドプログラムを作成する時、sleepとwaitの違いをよく無視して、非常に難しい問題を引き起こします。この二つの方法の違いを知ると、より良いプログラムを作成するのに役立ちます。
違い:
sleep()
wait()
sleepはThread類の方法で、スレッド自体の流れを制御します。
waitはobject類の方法で、主にスレッド間通信に用いられます。
sleep()睡眠時、対象錠を保持する。
wait()スリープ時、対象ロックを解除し、現在はその対象ロックを持っているスレッドを待機させ、他のスレッドがnotifyを起動するまで待つ(備考:タイムアウト起動も使用可能)。
同期コードブロックにアクセスできませんでした。
同期コードブロックにアクセス可能
コード:
違い:
sleep()
wait()
sleepはThread類の方法で、スレッド自体の流れを制御します。
waitはobject類の方法で、主にスレッド間通信に用いられます。
sleep()睡眠時、対象錠を保持する。
wait()スリープ時、対象ロックを解除し、現在はその対象ロックを持っているスレッドを待機させ、他のスレッドがnotifyを起動するまで待つ(備考:タイムアウト起動も使用可能)。
同期コードブロックにアクセスできませんでした。
同期コードブロックにアクセス可能
コード:
package com.jony.test;
public class ThreadTest implements Runnable {
int number = 10;
public void firstMethod() throws Exception {
System.out.println("first");
System.out.println(Thread.currentThread());
System.out.println(this);
synchronized (this) {
number += 100;
System.out.println(number);
notify();
}
}
public void secondMethod() throws Exception {
System.out.println("second");
System.out.println(Thread.currentThread());
System.out.println(this);
synchronized (this) {
/*
* sleep() , , ; wait() , 。 :
* (1)sleep
* (2)wait
* ( 2S, )
* ,
*/
//Thread.sleep(2000);
//this.wait(2000);// wait
this.wait();
System.out.println("Before: " + number);
number *= 200;
System.out.println("After: " + number);
}
}
@Override
public void run() {
try {
firstMethod();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
ThreadTest threadTest = new ThreadTest();
Thread thread = new Thread(threadTest);
System.out.println(Thread.currentThread());
//thread.run(); // , run
thread.start();// ( ), Java run
//Thread.sleep(1000);
threadTest.secondMethod();
}
}