问个Thread的小问题

nonon 2008-12-03 01:08:54
public class TestThread {
public static void main(String[] args){

MyThread t = new MyThread();
t.start();
System.out.println("3");
}
}
class MyThread extends Thread{
public void run(){
System.out.println("2");
}
}

为什么结果是先3 再2,怎么样才能先2 再3 阿?
不用 t.run()
...全文
92 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
ZiSheng 2008-12-03
  • 打赏
  • 举报
回复

public class test {
public static void main(String[] args){

MyThread t = new MyThread();
t.start();
try{
t.join();
}
catch(InterruptedException e){

}
System.out.println("3");
}
}
class MyThread extends Thread{
public void run(){
System.out.println("2");
}
}

JamesZou89 2008-12-03
  • 打赏
  • 举报
回复
看看 Thread 的API 把自定义的线程的优先级设定一下
guogaocheng 2008-12-03
  • 打赏
  • 举报
回复
忘记写catch了,呵呵!
guogaocheng 2008-12-03
  • 打赏
  • 举报
回复
//main方法也是一个线程

Java codepublic class TestThread {
public static void main(String[] args){

MyThread t = new MyThread();
t.start();
try{
Thread。sleep(2000);//mian线程睡2秒,这样main线程会让
出CPU,接着t线程得到CPU控制权,打印2
}
System.out.println("3");
}
}
class MyThread extends Thread{
public void run(){
System.out.println("2");
}
这样就能先2 再打印3
}

nonon 2008-12-03
  • 打赏
  • 举报
回复
实际上我想写一个Server 监听socket,每收到一个连接就建一个线程负责监听。用join必须结束一个连接,才能收下一个。
lgtwboy 2008-12-03
  • 打赏
  • 举报
回复
单纯的由执行时间所决定
main()要是从1打印到1000
那么 打印2 可能就出现在中间了
mizukusa 2008-12-03
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 dreamhunter_lan 的回复:]
首先、先打印哪个是控制不了的
用join()可以解决你的问题
Java codepublicclassTestThread {publicstaticvoidmain(String[] args){
MyThread t=newMyThread();
t.start();try{
t.join();
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("3");
}
}classMyThreadextendsThread{publicvoidrun(){
System.out.pri…
[/Quote]
正解
ssqtjffcu 2008-12-03
  • 打赏
  • 举报
回复
public class TestThread {
public static void main(String[] args) {

MyThread t = new MyThread();
t.start();
t.setPriority(8);
System.out.println("3");
}
}
class MyThread extends Thread{
public void run(){
System.out.println("2");
}
}
tanqimin 2008-12-03
  • 打赏
  • 举报
回复
主线程执行完打印任务,MyThread还没获得系统分配的空闲,所以会像楼主的情况一样,2楼正解
dreamhunter_lan 2008-12-03
  • 打赏
  • 举报
回复
首先、先打印哪个是控制不了的
用join()可以解决你的问题

public class TestThread {
public static void main(String[] args){
MyThread t = new MyThread();
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("3");
}
}
class MyThread extends Thread{
public void run(){
System.out.println("2");
}
}

62,615

社区成员

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

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