Java多线程基础学习(一)

public final native void notify()

注意:在notify()方法后,当前线程不会马上释放该对象锁,要等到执行notify()方法的线程将程序执行完,也就是退出同步代码块中。

 package wait.notify;
public class ThreadWaitNotifyTest {
final static Object object=new Object();
public static class T1 extends Thread{
public void run(){
System.out.println(System.currentTimeMillis()+": T1 start");
synchronized (object){
try {
System.out.println(System.currentTimeMillis()+": T1 wait");
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(System.currentTimeMillis()+": T1 end");
}
}
public static class T2 extends Thread{
public void run(){
System.out.println(System.currentTimeMillis()+": T2 start");
synchronized (object){
System.out.println("T2 synchonized code start.");
object.notify();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
System.out.println("T2 synchonized code end.");
} }
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis()+": T2 end");
}
}
public static void main(String[] args){
Thread thread1=new T1();
Thread thread2=new T2();
thread1.start();
thread2.start();
}
}

输出结果: