您的位置:首页 > 编程语言 > Java开发

Java牛角尖【008】: 可以通过调用一个线程的run方法启动一个线程吗?

2009-06-11 15:55 736 查看
我们知道,我们通过调用线程的start方法启动一个线程,那么,我们可以直接调用run方法来启动一个线程吗?

先看下面一段代码:

public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
TestThread tt = new TestThread();
tt.run();
}
}

class TestThread extends Thread {
static int i = 0;
final static int MAX_I = 10;

@Override
public void run() {
// TODO Auto-generated method stub
while (i < MAX_I) {
System.out.println(i++);
}
}
}


运行结果如下:

0
1
2
3
4
5
6
7
8
9


或许有人会得出结论,这样启动一个线程是可以的,我们再对程式稍做修改,大家就会发现一个问题:

public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
TestThread tt = new TestThread();
tt.run();
System.out.println("Printed by main thread");
}
}

class TestThread extends Thread {
static int i = 0;
final static int MAX_I = 10;

@Override
public void run() {
// TODO Auto-generated method stub
while (i < MAX_I) {
System.out.println(i++);
}
}

}


这里只在主线程中加入了一行代码,打印一行"Printed by main thread",运行代码,结果如下:

0
1
2
3
4
5
6
7
8
9Printed by main thread


熟练多线程开发的要发现问题了,为什么"Printed by main thread"会打印在最后一行呢?TestThread类中一直持有时间段吗?

我们对上面的代码进行分析,其实非常简单,这只是一个普通的类中方法的调用,其实是一个单线程的执行,我们来修改代码进一步验证这一点:

public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
TestThread tt = new TestThread();
tt.run();
System.out.println(Thread.currentThread().getName());
System.out.println("Printed by main thread");
}
}

class TestThread extends Thread {
static int i = 0;
final static int MAX_I = 10;

@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName());
while (i < MAX_I) {
System.out.println(i++);
}
}
}


这段代码分别在主线程和我们的TestThread的方法中打印当前线程名字,运行结果如下:

main
0 1 2 3 4 5 6 7 8 9main
Printed by main thread


在TestThread类和主线程中运行的是同一个线程,说明在直接调用run时是不能使用多线程的,那么把上面的run方法调用改为start方法的调动再看一下:

public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
TestThread tt = new TestThread();
tt.start();
System.out.println(Thread.currentThread().getName());
System.out.println("Printed by main thread");
}
}

class TestThread extends Thread {
static int i = 0;
final static int MAX_I = 10;

@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName());
while (i < MAX_I) {
System.out.println(i++);
}
}
}


运行结果如下:

main
Thread-0
0
1
2
3
4
5
6
7
8
Printed by main thread
9


很明显,这才是我们想看到的结果,所以结论是只有调用Thread的start方法,将线程交由JVM控制,才能产生多线程,而直接调用run方法只是一个普通的单线程程式。

下一篇: Java牛角尖【009】: 多线程中synchronized的锁定方式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐