java main是多线程的吗_java关于多线程 在main()方法中开启多个线程实例.start()方法后 主线程是什么状态?...

1.main线程不是守护线程,在main方法执行结束后就会死亡

2.

Thread.activeCount()返回的是当前线程所在的线程组下有多少个线程,至于线程是死是活它是不管的,

线程组(ThreadGroup)就是由线程组成的管理线程的类,这个类是java.lang.ThreadGroup类。

在Java中每一个线程都归属于某个线程组管理的一员,例如在

Thread.enumerate(Thread[])返回的是当前线程所在的线程组下活着的线程,将它们复制到传入的数组然后返回实际复制数。

3.题主程序中打印的Thread.activeCount()值一直为3,指的就是main线程组下面的线程1,2和main线程,而事实上main线程已经死亡了

4.不过目前JVM当中确实有三个线程在运行

可以参看:

JAVA虚拟机启动程序步骤:

(1) Main是启动时候的主线程,即程序入口

(2) 在main函数结束后,虚拟机会自动启动一个DestroyJavaVM线程,该线程会等待所有user thread 线程结束后退出(即,只剩下daemon 线程和DestroyJavaVM线程自己,整个虚拟机就退出,此时daemon线程被终止),因此,如果不希望程序退出,只要创建一个非daemon的子线程,让线程不停的sleep即可。

目前的三个线程是线程1,2和DestroyJavaVM线程

可以通过程序来证实这个结论

--------------------

public class ThreadDemo {

public static void main(String[] args) {

Thread t = Thread.currentThread();

t.setName("Admin Thread");

// set thread priority to 1

t.setPriority(1);

// prints the current thread

System.out.println("Thread = " + t);

//线程1

Thread threadA = new Thread(new Runnable(){

@Override

public void run() {

try {

for(;;)

{

Thread.sleep(3000);

}

} catch (InterruptedException e) {

e.printStackTrace();

}

}

});

//线程2

Thread threadB = new Thread(new Runnable(){

@Override

public void run() {

try {

for(;;)

{

Thread.sleep(3000);

int count = Thread.activeCount();

System.out.println("threadB:currently active threads = " + count);

Thread th[] = new Thread[count];

// returns the number of threads put into the array

Thread.enumerate(th);

// prints active threads

for (int i = 0; i < count; i++) {

System.out.println(i + ": " + th[i]);

}

}

} catch (InterruptedException e) {

e.printStackTrace();

}

}

});

//给线程命名

threadA.setName("Thread A");

threadB.setName("Thread B");

//启动线程

threadA.start();

threadB.start();

int count = Thread.activeCount();

System.out.println("currently active threads = " + count);

Thread th[] = new Thread[count];

// returns the number of threads put into the array

Thread.enumerate(th);

// prints active threads

for (int i = 0; i < count; i++) {

System.out.println(i + ": " + th[i]);

}

}

}

得出的结果是

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值