线程同步问题。。。。。。

ker0804 2007-08-22 04:48:40
想在分线程的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();}
}
}


}
}



}
...全文
194 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
dragon_up 2007-08-24
  • 打赏
  • 举报
回复
同意j2093(景天),简单容易实现.
加一个boolean标志位放在for()内,循环一次标志位就改变一次.
hl4967 2007-08-24
  • 打赏
  • 举报
回复

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();
}
}
}
}
愤怒的小蒋 2007-08-23
  • 打赏
  • 举报
回复
设一个boolean的标志位

ker0804 2007-08-22
  • 打赏
  • 举报
回复
th2 t2=new th2(); 这个没用 忘删了。

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧