java多线程问题

byfox 2008-01-30 01:07:53

public class test {

/**
* @param args
*/
public static void main(String[] args) {
Thread1 t1=new Thread1();
Thread t2=new Thread(new Thread2());
t1.start();
t2.start();


}
}


class Thread1 extends Thread{

public void run(){
System.out.println("Thread1 is runing");
}

}


class Thread2 implements Runnable {

public void run() {
System.out.println("Thread2 is runing");
}

}


控制台看只显示
Thread1 is runing
Thread2 is runing
上课看老师做的都是交替的出现除非手动停止,我自己做为什么只出现这两行,请教~

...全文
79 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
yuanqingfei 2008-01-30
  • 打赏
  • 举报
回复
恩,至于是不是交替出现,实际上是具有偶然性的。
byfox 2008-01-30
  • 打赏
  • 举报
回复
感谢楼上的热心回答,的确是这样,参照2楼的例子也轻松搞定`
老紫竹 2008-01-30
  • 打赏
  • 举报
回复
一直执行run()方法
否!

只运行1次run()方法。 Only One Time;
byfox 2008-01-30
  • 打赏
  • 举报
回复
线程对象调用start()方法不就是激活线程吗,然后一直执行run()方法。
不用线程直接写个循环不也可以一直输出吗。可能我理解问题了。在研究一下
老紫竹 2008-01-30
  • 打赏
  • 举报
回复
System,out.println 只能输出一次,不可能一直不断的打印,所以只能使用循环让其不断的运行。
OVER
byfox 2008-01-30
  • 打赏
  • 举报
回复
必须用循环才能交替执行吗,我记得老师没用循环像我写那样,两个线程就自动交替执行。。
cursor_wang 2008-01-30
  • 打赏
  • 举报
回复
public   class   test   { 

/**
* @param args
*/
public static void main(String[] args) {
Thread1 t1=new Thread1();
Thread t2=new Thread(new Thread2());
t1.start();
t2.start();


}
}


class Thread1 extends Thread{

public void run(){
while(true){
try{
System.out.println("Thread1 is runing");
this.currentThread().sleep(1000);
}catch(Exception e){
System.out.println(e);
}

}

}
}


class Thread2 implements Runnable {

public void run(){
while(true){
try{
System.out.println("Thread2 is runing");
Thread.currentThread().sleep(1000);
}catch(Exception e){
System.out.println(e);
}
}

}

}

62,623

社区成员

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

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