日期:2014-05-20 浏览次数:21039 次
/* ThreadCommunication1.java
*/
package cn.itcast;
public class ThreadCommunication1
{
public static Object forLock=new Object();
public static boolean bool =true;
public static void main(String[] args)
{
Thread thread=new Thread(new Runnable()
{
@Override
public void run()
{
for(int i=0;i<20;i++)
{
//ThreadCommunication1.forLock=this.getClass();
synchronized (ThreadCommunication1.forLock)
{
while(bool)
{
try
{
ThreadCommunication1.forLock.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
for(int j=0;j<10;j++)
{
System.out.println("thread:"+Thread.currentThread()+
"----"+j+"----"+i);
}
bool=true;
ThreadCommunication1.forLock.notify();
}
}
}
});
thread.start();
for(int j=0;j<20;j++)
{
synchronized(ThreadCommunication1.forLock)
{
while(!bool)
{
try
{
ThreadCommunication1.forLock.wait();
}
catch (InterruptedException e)
{
System.out.println("hh");
e.printStackTrace();
}
}
for(int i=0;i<10;i++)
{
System.out.println("main:"+Thread.currentThread()+"----"+i+"----"+j);
}
bool=false;
ThreadCommunication1.forLock.notify();
}
}
}//end main
}//end class