What is the correct background process behavior for an application other than the Java GUI?

How can a Java command-line application do background work without resources? Should it use sleep () in a loop or is there a more elegant / efficient way?

+3
source share
4 answers

Some heuristics:

  • Do not try to make planning decisions in your application. The operating system scheduler is better than yours. Let him do his job.
  • , . , n , , , . .
  • , , . .
  • -. . , -, , . (, .)
  • . ; . , , java.util.concurrent.

, ...

+9

sleep(), . , - , , , ..

, , - , Thread.yield(). , . , .

: myThread.setPriority(Thread.MIN_PRIORITY);

, . " ". , (GUI CLI) - .

+3

. ExecutorService... :

ExecutorService service = Executors.newCachedThreadPool();

Callable<Result> task = new Callable<Result>() {
    public Result call() throws Exception {
        // code which will be run on background thread
    }
};

Future<Result> future = service.submit(task);

// Next line wait until background task is complete
// without killing CPU. Of course, you can do something
// different here and check your 'future' later.
//
// Note also that future.get() may throw various exceptions too,
// you'll need to handle them properly

Result resultFromBackgroundThread = future.get();

Java 5, ExecutorService, Callable, Future .. java.util.concurrent.

+2

- , , ( ).

sleep() . , โ€‹โ€‹, .

+1

All Articles