class MyThread_1 extends Thread
{
Object lock;
public MyThread_1(Object o)
{
lock=o;
}
public void run()
{
try
{
synchronized(lock)
{
System.out.println("Enter Thread_1 and wait");
lock.wait();
System.out.println("be notified");
}
}catch(InterruptedException e){}
}
}
class MyThread_2 extends Thread
{
Object lock;
public MyThread_2(Object o)
{
lock=o;
}
public void run()
{
synchronized(lock)
{
System.out.println("Enter Thread_2 and notify");
lock.notify();
}
}
}
class MyThread
{
public static void main(String[] args)
{
int[] in=new int[0];//notice
MyThread_1 t1=new MyThread_1(in);
MyThread_2 t2=new MyThread_2(in);
t1.start();
t2.start();
}
}output:
Enter Thread_1 and wait
Enter Thread_2 and notify
be notified
本文通过两个线程实例展示了Java中线程间的同步与唤醒机制。一个线程等待对象锁,另一个线程获取同一对象锁后调用notify()方法唤醒等待的线程。文章通过具体代码演示了这一过程,并提供了运行结果。

231

被折叠的 条评论
为什么被折叠?



