java多线程问题

[复制链接]
查看11 | 回复4 | 2010-10-26 14:18:30 | 显示全部楼层 |阅读模式
class thread1 extends Thread{
thread1(String str){
this.setName(str);
}
public void run(){
try{

for(int x = 0;x<10;x++){
sleep(1000);
System.out.println(x+""+getName());
}

}
catch(InterruptedException e){

System.out.println(e.toString());
}
}
}
class thread2 implements Runnable{
String Name;
thread2(String str){
Name = str;
}
public void run(){
try{
for(int x = 0;x<10;x++){
Thread.sleep(1000);
System.out.println(x+""+Name);
}
}
catch(InterruptedException e){
System.out.println(e.toString());
}
}
}
public class threadDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
thread1 t11 = new thread1("thread11");
thread1 t12 = new thread1("thread12");
thread2 t21 = new thread2("thread21");
thread2 t22 = new thread2("thread22");
t11.start();
t12.start();
t21.run();
t22.run();
}
}
结果为什么是先t11,t12,t21同步无序进行,然后t22自己单独运行??

回复

使用道具 举报

千问 | 2010-10-26 14:18:30 | 显示全部楼层
LZ直接调用run()方法是不对的。 t21.run(); t22.run();这是方法调用,而不是开启一个线程。当你调用Thread类的start()方法时,才是启动这个线程。以下是粘贴别人的start()和run()方法的区别,LZ好好看看吧。。。首先, 之所以出现线程,就是为了更好的利用CPU,让她更加“精明”的干活。 通过调用Thread类的start()方法来启动一个线程, 这时此线程是处于就绪状态, 并没有运行。 然后通过此Thread类调用方法run()来完成其运行操作的, 这里方法run()称为线程体, 它包含了要执行的这个线程的内容, Run方法运行结束, 此线程
回复

使用道具 举报

千问 | 2010-10-26 14:18:30 | 显示全部楼层
在这个程序中,一共有5个线程,主函数一个,另外你new 出来了4个,而这四个都是不同的线程;而这5个线程之间的关系是谁先抢到时间片谁就先执行,比如说,t11先得到时间片,那么就进行下去,但是一到for循环运行一次的时候,时间片突然就给t12得到了,那么就轮到t12运行了,同样t12可能运行到for那里又被t11从新得到的话,t11就会继续刚才那里执行下去,以
回复

使用道具 举报

千问 | 2010-10-26 14:18:30 | 显示全部楼层
本例共有5个线程,但只有3个有运行:t11,t12和main t11.start()t12.start()使得t11,t12和主线程main通过获得时间片“同步”运行;因为main方法里调用了t21.run()方法,所以看到的现象是t11,t12,t21同步无序运行,实际上t21线程并未启动,只是main方法里调用了t21.run()
回复

使用道具 举报

千问 | 2010-10-26 14:18:30 | 显示全部楼层
wangttkk88回答的不错
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行