java 在主线程运行吗,如何在Java中与主线程分开运行线程?

The goal is to be able to invoke execution of a separate thread from within the main class.

Some context:

I have a program that must run a process.

The process (a cmd one) should run only when the main program is done executing and is unloaded from memory.

What code should I include in the main class?

解决方案

If you mean: how can I start a Java thread that will not end when my JVM (java program) does?.

The answer is: you can't do that.

Because in Java, if the JVM exits, all threads are done. This is an example:

class MyRunnable implements Runnable {

public void run() {

while ( true ) {

doThisVeryImportantThing();

}

}

}

The above program can be started from your main thread by, for example, this code:

MyRunnable myRunnable = new MyRunnable();

Thread myThread = new Thread(myRunnable);

myThread.start();

This example program will never stop, unless something in doThisVeryImportantThing will terminate that thread. You could run it as a daemon, as in this example:

MyRunnable myRunnable = new MyRunnable();

Thread myThread = new Thread(myRunnable);

myThread.setDaemon(true); // important, otherwise JVM does not exit at end of main()

myThread.start();

This will make sure, if the main() thread ends, it will also terminate myThread.

You can however start a different JVM from java, for that you might want to check out this question:

Launch JVM process from a Java application use Runtime.exec?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值