Given:
1. public class Threads5 {
2. public static void main (String[] args) {
3. new Thread(new Runnable() {
4. public void run() {
5. System.out.print("bar");
6. }}).start();
7. }
8. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes normally and prints "bar".
D. The code executes normally, but nothing prints.
如果在start后加上System.out.println("main end"); 你会发现打印的结果是
main end
bar
这说明打印bar时,main进程已经结束了。而JVM会在所有的非守护线程(用户线程)执行完毕后退出
c#也是一样,测试代码如下:
using System;
using System.Threading;
namespace dayapp1
{
class Program
{
static void Main(string[] args)
{
Thread t = new Thread(print);
t.Start();
System.Console.WriteLine("main end");
System.Console.ReadKey();
}
public static void print() {
System.Console.WriteLine("print");
}
}
}
问题来了,如果要让Main方法等待thread执行结束呢?那么要加上t.join();
Thread t = new Thread(print);
t.Start();
t.Join();
System.Console.WriteLine("main end");
System.Console.ReadKey();
package com.liu1;
public class Starter extends Thread {
private int x = 2;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
new Starter().makeItSo();
}
public Starter(){
x = 5;
start();
}
public void makeItSo() throws Exception{
join();
x = x -1;
System.out.println(x);
}
public void run(){ x*=2;}
}
输出结果是什么呢?有点绕啊,呵呵。首先调用Starter的构造方法,x值变成5,然后调用start方法,此时会调用run方法,x值变成10。最后调用makeItSo方法所以最后值是9。