0

Suppose I have a class which has a main method like below and that hoge.hoge() takes long time to complete.

public static void main(String[] args){
 hoge.hoge();
}

This application will be executed from the command line. I would like the application to immediately become a background task, exactly as if someone had executed:

java AboveClass &

I.e. the user should be returned back to the prompt. Is there a way I can achieve this in Java?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
kensuke1984
  • 949
  • 1
  • 11
  • 21
  • 1
    Can you please elaborate the issue . – Kick Mar 23 '15 at 09:35
  • Is this question relevant to your problem: http://stackoverflow.com/questions/12551514/create-threads-in-java-to-run-in-background – gilleain Mar 23 '15 at 09:40
  • It's probably best if you supply a script for your users to run, which starts the Java program and backgrounds it. – Duncan Jones Mar 23 '15 at 09:42
  • 1
    You are mixing up two different topics. Using the "&" character is a Unix feature; it simply puts the started job into the background. This has nothing to do with the fact that Java allows you to create its own threads. – GhostCat Mar 23 '15 at 09:44
  • @kensuke1984 I have re-written your question to be easier to understand. If I've got anything wrong, please [edit] the question and correct it. – Duncan Jones Mar 23 '15 at 09:49
  • Thank you @Duncan nothing wrong at all. – kensuke1984 Mar 24 '15 at 01:38
  • @gilleain yes but if i do this, the prompt does not come back until the thread ends. Thank you! – kensuke1984 Mar 24 '15 at 01:41
  • @EddyG yeah maybe I should understand the fact java runs on OS more carefully.. thank you – kensuke1984 Mar 24 '15 at 01:43

1 Answers1

1

Unfortunately, no, there is no such way to make the task into a background task. You could try creating a thread (and make it a daemon thread), but I think you'll find that even then if you return from the main method and the thread is still running, the program does not return to the prompt.

@Duncan suggested supplying a script that your users can run, which starts the Java program in the background. I recommend that approach.

If you want an all-Java solution, you could try creating the script in Java. See How to execute system commands (linux/bsd) using Java for how to execute commands from a Java program. So, you would execute "java ClassName &" from the Java program then. Not the prettiest solution, but it works. Of course it requires that the "java" command is in the path.

Community
  • 1
  • 1
juhist
  • 4,210
  • 16
  • 33