java并发编程学习(4)

构造Thread对象

如下代码创建并打印Thread对象的名称

public class CreateThread {

    public static void main(String[] args) {
        Thread t = new Thread();
        Thread t1 = new Thread();
        t.start();
        t1.start();

        System.out.println(t.getName());
        System.out.println(t1.getName());
    }

结果为

Thread-0
Thread-1

通过查看源码发现

/**
     * Allocates a new {@code Thread} object. This constructor has the same
     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
     * {@code (null, target, gname)}, where {@code gname} is a newly generated
     * name. Automatically generated names are of the form
     * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
     *
     * @param  target
     *         the object whose {@code run} method is invoked when this thread
     *         is started. If {@code null}, this classes {@code run} method does
     *         nothing.
     */
    public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }
 /* For autonumbering anonymous threads. */
    private static int threadInitNumber;
    private static synchronized int nextThreadNum() {
        return threadInitNumber++;
    }
public class ThreadCreate {
    public static void main(String[] args) {
        Thread t = new Thread();
        t.start();
        System.out.println(t.getThreadGroup());
        System.out.println(Thread.currentThread().getName());
        System.out.println(Thread.currentThread().getThreadGroup().getName());


    }
}
java.lang.ThreadGroup[name=main,maxpri=10]
main
main
  1. 如果创建Thread时没有指定名称,将会默认以Thread-开头,从0开始计数
  2. 如果在构造Thread的时候没有传递或者没有覆写run方法,改Thread将不会调用任何东西,如果传递了Runnable接口实例或者覆写了Thread的run方法,则会执行该逻辑单元
  3. 如果构造线程对象时未传入ThreadGroup,则Thread会默认获取父线程的ThreadGroup作为该线程的ThreadGroup
  4. 构造Thread的时候传入stacksize代表该线程占用stack大小,如果没有指定,默认是0,0代表会忽略该参数该参数会被JNI函数去使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值