我想从我的主java程序中产生一个Java线程,并且该线程应该单独执行而不会干扰主程序。这是应该的:在java中创建线程以在后台运行
- 用户
- 启动主程序做一些业务工作,并应创建一个新的线程,可能只要线程被创建时,处理后台进程
- 主程序不应该等到产生的线程完成。事实上,它应该是无缝..
我想从我的主java程序中产生一个Java线程,并且该线程应该单独执行而不会干扰主程序。这是应该的:在java中创建线程以在后台运行
一个直接的方法是自己手动生成线程:
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
runYourBackgroundTaskHere();
}
};
new Thread(r).start();
//this line will execute immediately, not waiting for your task to complete
}
另外,如果你需要生成多个线程或需要做的反反复复,你可以使用更高级别的并发API和执行服务:
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
runYourBackgroundTaskHere();
}
};
ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(r);
//this line will execute immediately, not waiting for your task to complete
}
这是使用匿名内部类创建线程的另一种方式。
public class AnonThread {
public static void main(String[] args) {
System.out.println("Main thread");
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Inner Thread");
}
}).start();
}
}
,如果你喜欢做它在Java 8路,你能做到像这样简单:
public class Java8Thread {
public static void main(String[] args) {
System.out.println("Main thread");
new Thread(this::myBackgroundTask).start();
}
private void myBackgroundTask() {
System.out.println("Inner Thread");
}
}
[Java中的线程(的
可能重复http://stackoverflow.com/questions/2865315/threads-in-java) –
你看过[Java Tutorials Concurrency section](http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html)吗? – Keppil