多线程线程(wait、notify)
***************************
相关方法
public class Object {
********
线程唤醒
@HotSpotIntrinsicCandidate
public final native void notify();
@HotSpotIntrinsicCandidate
public final native void notifyAll();
********
线程等待
public final void wait() throws InterruptedException {
wait(0L);
}
public final native void wait(long timeoutMillis) throws InterruptedException;
public final void wait(long timeoutMillis, int nanos) throws InterruptedException {
说明:wait()、notify()、notifyAll()方法需要在同步语句里面使用;
wait()会立刻释放锁;notify() 、notifyAll()等到同步语句执行完释放锁
****************************
示例
class Test{
synchronized void test(){
try{
System.out.println("进入同步方法test:"+System.currentTimeMillis());
Thread.sleep(1000);
this.wait();
System.out.println("结束同步方法test:"+System.currentTimeMillis());
}catch (Exception e){
e.printStackTrace();
}
}
synchronized void test2(){
try{
System.out.println("进入同步方法test2:"+System.currentTimeMillis());
this.notify();
Thread.sleep(10000);
System.out.println("结束同步方法test2:"+System.currentTimeMillis());
}catch (Exception e){
e.printStackTrace();
}
}
}
class Test1 implements Runnable{
private Test test;
Test1(Test test){
this.test=test;
}
@Override
public void run() {
test.test();
}
}
class Test2 implements Runnable{
private Test test;
Test2(Test test){
this.test=test;
}
@Override
public void run() {
test.test2();
}
}
public class ThreadTest6 {
public static void main(String[] args){
Test test=new Test();
Test1 t1=new Test1(test);
Test2 t2=new Test2(test);
Thread thread=new Thread(t1);
Thread thread2=new Thread(t2);
thread.start();
thread2.start();
}
}
**************************
控制台输出
进入同步方法test:1568815070367
进入同步方法test2:1568815071390
结束同步方法test2:1568815081391
结束同步方法test:1568815081392