想在分线程的for循环完成一次后,跳到主线程运行。怎么实现
下面代码是分线程运行完了 主线程才运行,怎么修改????
package test;
public class threadtest{
Object o=new Object();
public threadtest(){ th1 t1=new th1(); th2 t2=new th2(); t1.start(); synchronized(o){
try{
o.wait();
}catch(Exception e3){}

for(int i=0;i<1000;i++){
System.out.println("主线程执行");
if(i==999)
System.out.println("主线程执行完毕。");
}
}
System.out.println("主线程结束。"); }
public static void main(String[] args){
new threadtest();
} class th1 extends Thread  {
public void run(){
System.out.println("线程1开始");
for(int j=0;j<2;j++){
synchronized(o){
for(int i=0;i<800;i++){
System.out.println("线程 1 执行");
if(i==799)
System.out.println("线程 1 执行完毕。");
}
System.out.println("循环完毕");
o.notify();
try{sleep(1000);}catch(InterruptedException e){e.printStackTrace();}
}
}


}
}



}

解决方案 »

  1.   

    th2 t2=new th2();   这个没用 忘删了。
      

  2.   


    public class TestThread
    {
            Object o=new Object();
            public TestThread()
            {
              th1 t1=new th1(this);
               t1.start();         synchronized(this)
             {
               try
               {
                  this.wait();
               }
               catch(Exception e3){e3.printStackTrace();}           for(int i=0;i<1000;i++)
               {
    //              System.out.println("主线程执行");
                 if(i==999)
                   System.out.println("主线程执行完毕。");
               }
             }
             System.out.println("主线程结束。");
            }
      
            public static void main(String[] args)
            {
                    new TestThread();
            }        class th1 extends Thread
            {
                    TestThread th1=null;
                    public th1(TestThread th1)
                    {
                      this.th1 =  th1;
                    }
                    public void run()
                    {
    //                  System.out.println("线程1开始");
                      for(int j=0;j<2;j++)
                      {
                        
                          for(int i=0;i<800;i++)
                          {
    //                        System.out.println("线程 1 执行");
                            if(i==799)
                              System.out.println("线程 1 执行完毕。");
                          }
                          System.out.println("循环完毕");                      try{sleep(1000);}catch(InterruptedException e){e.printStackTrace();}
                        }
                        synchronized(th1)
                        {
                          th1.notify();
                        }
                      }
            }
          }
      

  3.   

    同意j2093(景天),简单容易实现.
    加一个boolean标志位放在for()内,循环一次标志位就改变一次.