//求解,谢谢.
public class Threadsynch
{
public static void main(String[] args) {
final ThreadCode tc = new ThreadCode();//说这里有错,我不知错在哪。。。也不太明白为什么要加final
new Thread(
new Runnable(){
public void run()
{
for(int i=1;i<=50;i++)
{
tc.sub(i);
}
}
}).start();
for(int i=1;i<=50;i++)
{
tc.main(i);
}
}
class ThreadCode
{
private boolean trade = true;
public synchronized void sub(int i)
{
while(!trade)
{
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=10;j++)
{
System.out.println("sub thread:"+j+"次数"+i);
}
trade = false;
this.notify();
}
public synchronized void main(int i)
{
while(trade)
{
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=30;j++)
{
System.out.println("main thread:"+j+"次数"+i);
}
trade = true;
this.notify();
}
}
}
|