Nol*_*esh 6 java multithreading
我想知道如何通知另一个线程的最佳方法。例如,我有一个后台线程:
public void StartBackgroundThread(){
new Thread(new Runnable() {
@Override
public void run() {
//Do something big...
//THEN HOW TO NOTIFY MAIN THREAD?
}
}).start();
}
Run Code Online (Sandbox Code Playgroud)
完成后必须通知主线程吗?如果有人知道最好的方法,我将不胜感激!
只需调用notify()
public void run() {
try {
while ( true ) {
putMessage();
sleep( 1000 );
}
}
catch( InterruptedException e ) { }
}
private synchronized void putMessage() throws InterruptedException {
while ( messages.size() == MAXQUEUE )
wait();
messages.addElement( new java.util.Date().toString() );
notify();
}
Run Code Online (Sandbox Code Playgroud)