不知是否是需要结果,说明见注释,问题是最后一个阻塞无人唤醒。class MyThread extends Thread{ private int i = 1;
private static Object ob=new Object(); //建立个公共对象,用于实现互斥
public MyThread(String name)
{
super(name);
//i=1;
}
public void print()
{
synchronized(ob){ //使用ob对象实现线程的互斥
while(true)
{
System.out.println(i+"\t"+getName());
if(i%10 == 0) //当一个线程输出1-10时就处于阻塞状态,唤醒另一个线程。
{ //当另一个线程也输出1-10时,同样处于阻塞状态,唤醒前面那个线程输出11-20,....
ob.notify(); //首先唤醒其他线程,否则先自己阻塞了如何唤醒他人
System.out.println("i:"+i);
try{
ob.wait();
}catch(InterruptedException e){
System.out.println(e.getMessage());
}
System.out.println("*************");
}
if(i ==100)
break;
i++;
}
}
}
public void run()
{
print();
}
}public class MyThreadTest{
public static void main(String[] args)
{
Thread first = new MyThread("first");
Thread second = new MyThread("second");
first.start();
second.start();
}
}
private static Object ob=new Object(); //建立个公共对象,用于实现互斥
public MyThread(String name)
{
super(name);
//i=1;
}
public void print()
{
synchronized(ob){ //使用ob对象实现线程的互斥
while(true)
{
System.out.println(i+"\t"+getName());
if(i%10 == 0) //当一个线程输出1-10时就处于阻塞状态,唤醒另一个线程。
{ //当另一个线程也输出1-10时,同样处于阻塞状态,唤醒前面那个线程输出11-20,....
ob.notify(); //首先唤醒其他线程,否则先自己阻塞了如何唤醒他人
System.out.println("i:"+i);
try{
ob.wait();
}catch(InterruptedException e){
System.out.println(e.getMessage());
}
System.out.println("*************");
}
if(i ==100)
break;
i++;
}
}
}
public void run()
{
print();
}
}public class MyThreadTest{
public static void main(String[] args)
{
Thread first = new MyThread("first");
Thread second = new MyThread("second");
first.start();
second.start();
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货