62,621
社区成员
发帖
与我相关
我的任务
分享
class th1 implements Runnable
{
private static int count;
th1()
{
count=0;
}
public static int getCount(){return count;}
public synchronized void waitme()
{
count++;
//if (count%5==0)
notifyAll();
System.out.print(count+" ");
}
public void run()
{
for(;;){
try{
Thread.sleep(1000);
waitme();
}catch(InterruptedException e){return;}
}}
}
class th2 implements Runnable
{
public synchronized void act()
{
try {
while(th1.getCount()%5!=0)
{
wait();
}
System.out.print("Finally"+th1.getCount()+" ");
// Thread.sleep(900);
}catch (InterruptedException e) {
return;
}
}
public void run()
{
for(;;){
act();
}
}
}
public class waitwait {
public static void main(String args[])
{
th1 t1=new th1();
th2 t2=new th2();
new Thread(t2).start();
new Thread(t1).start();
}
}
//由于1秒和5秒的类一样,所以就写成一个类
class SecsThread extends Thread{
private final String name;
private PrintSecs ps;
public SecsThread(String name; PrintSecs ps){
this.name = name;
this.ps = ps;
}
public void run{
try{
while(true)
ps.printSece(name);
}catch(InterruptedException e){}
}
}
class PrintSecs{
private final Object lock = new Object();
private int count = 0;
public void printSece(String stname) throws InterruptedException{
synchronized(lock){
//如果1secs取5的模等于0并且当前线程是1secs,那就唤醒其他线程,自己等待
if((count%5 == 0) && (stname.equalsIgnoreCase("1secs"))){
lock.notify();
lock.wait();
//同理,如果线程是5secs,那也是唤醒其他线程,自己等待
}else if(stname.equalsIgnoreCase("5secs"))){
lock.notify();
lock.wait();
}
System.out.println(stname + " - - " + count);
count++;
}
Thread.sleep(1000);//睡1秒
}
}
public static void main(String[] args){
PrintSecs ps = new PrintSecs();
SecsThread st1 = new SecsThread("1Secs",ps);
SecsThread st5 = new SecsThread("5Secs",ps);
st1.start();
st5.start();
}