OCJP题库知识点总结(1)

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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值