Java 1.5 Tiger A Developers Notebook [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Java 1.5 Tiger A Developers Notebook [Electronic resources] - نسخه متنی

David Flanagan, Brett McLaughlin

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید








10.8 Executing Tasks Without an ExecutorService


So what happens when you just have one little Callable object that you
want to execute, and you don't need the overhead of ExectorService?
Well, it seems those Sun guys thought of everything (except perhaps
open sourcing Java)you use FutureTask.


10.8.1 How do I do that?


java.util.concurrent.FutureTask can be wrapped around Callable
objects, allowing them to behave like a Future implementation returned
from ExecutorService.submit( ). The syntax is similar as well:


FutureTask<BigInteger> task =
new FutureTask<BigInteger>(new RandomPrimeSearch(512));
new Thread(task).start( );
BigInteger result = task.get( );

The methods available to FutureTask are similar to Future, so I'll leave it to you to check out the Javadoc. With the details from Using Callable Objects, you shouldn't have any problems.


10.8.2 What about...


...good old Runnable? Fortunately, plain old Thread and Runnable didn't
get left out of the mix. You can wrap a FutureTask around a Runnable
object just as easily as you can around a Callable object, and the same
functionality applies. However, since Runnable's run( ) method doesn't return a result, the constructor is a bit different:


FutureTask<String> task =
new FutureTask<String>(new MyRunnableObject, "Success!");

You have to supply a value to the constructor, of the type specified by
your parameterization (in this example, a String), which is returned by
get( ) if execution is successful. While the above example is valid, there
are really only two common variants when using Runnable FutureTasks:


FutureTask<Object> task = new FutureTask<Object>(runnable, null);
FutureTask<Boolean> task = new FutureTask<Boolean>(runnable, true);

The first allows for discarding the result of get( ) altogether, and the second provides a true/false check for the result of get( ). You'd do well to use one of these yourself.


/ 131