线程调用问题

kill8108 2005-02-26 12:29:59
设一个类A,A中有一个方法output(),然后一个类B继承A,当B运行时,每隔3秒就运行一次A中的output()方法,要用线程技术来设置!

class A implements Runnable
{
public void run()
{
new A().output();

}
public synchronized void output()
{
System.out.println("123456789");
}
};
public class B1 extends A
{

public static void main(String[] args)
{
while(true)
{
try{Thread.sleep(3000);}
catch(Exception e){}
Thread t = new Thread(new A());
t.start();
//t.start();
//t.start();
}
}
}



这种程序设计应怎么样设置更更好呢,我写了个但不够理想吧,大家看下有什么不好之处请指点,还有一个问题就是若我t.start()----后面两个没注释掉,将会出现Thread的错误,怎么修改才可以运行呢!

...全文
81 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
ainice 2005-02-26
  • 打赏
  • 举报
回复
这样写:
class A extends Thread
{
public void run()
{
wile(true){
output();
try{
sleep(3000);

}catch(InterruptedException ie){System.out.println(ie.getMessage());}
}
public synchronized void output()
{
System.out.println("123456789");
}
}
public class B1 extends A
{

public static void main(String[] args)
{
B1 b=new B1();
b1.start();
}
}
一般不是多继承就没必要实现那个runnable接口,直接继承thread类
chenhao1949 2005-02-26
  • 打赏
  • 举报
回复
就單純你這個例子來說,public class B1 extends A
是多於的!

public class B1
{

public static void main(String[] args)
{
B1 bb=new B1();
while(true)
{
try{Thread.sleep(3000);}
catch(Exception e){}
bb.output();
}
}
public void output()
{
System.out.println("1");
}
}


有很多寫法,你還可以用Timer/TimerMask

最好是用runnable接口

62,615

社区成员

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

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