Add Multithreading Function to Java Application using ExecutorService
By admin on Sep 28, 2007 in Java, Programming
In my previous post, I showed you how to do a graceful shutdown of Java application. Now I am going to add multithreading functionalities to the simple example that I developed.
In SampleApp, I declared an instance of ExecutorService, and then I created a default pool size of 10.
private ExecutorService pool;
public SampleApp() {
// Create the thread pool
pool = Executors.newFixedThreadPool(10);
}
In the start method, I submitted the tasks to be executed to the thread pool.
List futureList = new LinkedList();
for (int i = 0; i < 10; i++) {
ProcessorTask task = new ProcessorTask(String.valueOf(i));
Future future = pool.submit(task);
futureList.add(future);
}// You can get the result back from the thread
for (Future future : futureList) {
try {
// Wait with a time out if necessary
//Object obj = future.get(5, TimeUnit.SECONDS);
Object obj = future.get();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
} catch (ExecutionException e) {
System.out.println(e.getMessage());
}
}pool.shutdown();
After submitting the tasks, I can use the Future to return value from the thread.
ProcessorTask is simply a class that extends Runnable which implements the run method.
public class ProcessorTask implements Runnable {
private String name;
public ProcessorTask(String taskName) {
this.name = taskName;
}public void run() {
System.out.println(“Sleeping for 5 seconds for task ” + name);
try {
Thread.sleep(5000);
System.out.println(“Done sleeping for 5 seconds for task ” + name);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
Popularity: 100% [?]
kookimebux | Feb 1, 2009 | Reply
Hello. And Bye.
blitlytam | Feb 3, 2009 | Reply
Guys,
I am new on this fantastic forum twit88.com
and just would like to introduce myself here.
blitlytam
____________________________________________
Networking GreatBlogging Posts Comments Site Bloggers Blogging Zoom Day Traffic
osobo | Feb 17, 2009 | Reply
Новый способ давления на кандидата на пост Главы г. Химки
Новый способ “наказать” тех, кто посмел участвовать в выборной кампании не на стороне действующей власти изобрели правоохранительные органы г.о. Химки.
Руководствуясь не нормой закона, а чьей-то “волей” сотрудники милиции решили “проверить” все фирмы, внесшие денежные средства в избирательный фонд неудобных кандидатов.
Начались “проверки” с телефонных звонков – где директор, сколько человек работает на фирме. После чего последовали “письма счастья” с просьбой предоставить всю бухгалтерскую документацию, учредительные документы фирмы, и даже, план экспликации БТИ.
Такие запросы химкинским фирмам рассылает 1 отдел Оперативно-розыскной части № 9 Управления по налоговым преступлениям ГУВД Московской области за подписью начальника подполковника милиции Д.В. Языкова.
И всё это в то время, когда Президент дал прямое указание правоохранительным органам о прекращении всех незаконных проверок малого и среднего бизнеса. С это целью внесены изменения в Федеральный закон “О милиции” – из статьи 11 этого закона исключены пункты 25 и 35, на основании которых ранее правоохранительные органы имели право проверять финансово-хозяйственную деятельность предприятий.
Видно, об изменениях действующего законодательства местные правоохранительные органы не уведомлены. И не смотрят телепередачи с выступлениями Президента.
Может быть, эта публикация подвигнет их к исполнению указаний Президента, а также к изучению и соблюдению действующего законодательства
olyaseksa | Mar 13, 2009 | Reply
вас такое интересует секс фото огурец ?
TogsTeaxJeono | Mar 20, 2009 | Reply
very intresting
Upholemolla | Apr 9, 2009 | Reply
i wont dance lyrics frank sinatra dance dance revolution max 2 mp3 elevator mp3 download arctic bet dance fl good i look monkey dance with somebody who love me
age angeles club dance in los download immortal technique dance with the devil digital music download dance dance revolution ultramix song list barbers adagio for string dance mix
Madisonmay | Apr 10, 2009 | Reply
http://www.youtube.com/watch?v=3szYed_5o7o – How to Make Money Online
Глеб | Apr 10, 2009 | Reply
Блин… Реально красиво написано! Все это так знакомо…и правдиво!
BillZolozx | Apr 17, 2009 | Reply
SeVeS.Ru – очень интересный портал. У нас нет рекламы, но есть очень много интересного. Мы собрали только лучшее
И вы не останетесь равнодушными к огромному архиву HD фильмов и концертных выступлений на HD-Best.Ru
Arbicainarf | Apr 21, 2009 | Reply
Hey Everbody
I just became a member of this forum
Great work by the admin, mods and seriously every member around.
A few days ago I read that there is a treatment for diabetes on http://www.healthcaredaily.org
Is this way of curing diabetes mentioned actually true, If so I should have found out earlier! The source looks like a reliable healthcare news website
Could you someone tell me if this healthcare information is for real?
Thanks
Arbicainarf
heippepsivand | Apr 22, 2009 | Reply
Когда вы играете в онлайн игры, то посетите статистику онлайг игр
Статистика таких игр вдруг Neverlands, dwar, ganjawars.
Прочтите свежие новости онлайн игр и многое другое.
UniofAccini | Apr 24, 2009 | Reply
I’m the only one in this world. Can please someone join me in this life? Or maybe death…
TRABEMONANARE | Aug 7, 2009 | Reply
Играйте в азартные игры. Porek, Tehas holdem, бртдж, BlackJack, игровые автоматы flash и многое другое
ksvfmdsnvmn | Dec 28, 2009 | Reply
teen lesbians finger fucking
ZOChQsiAwzIaAksOeG | Feb 9, 2010 | Reply
wzyHyz asian models pictures
CnIXwz girl models free
NAPtIFhAwzPyQCHACI | Feb 9, 2010 | Reply
wzIzum asian models pictures
byURwz girl models free
KAMjgMoFwkvcoDQBUI | Feb 14, 2010 | Reply
wkNvAZ asian models pictures
GuGwwk girl models free
lKyZqocUwkvIGcvNOm | Feb 14, 2010 | Reply
wkXUDg asian models pictures
STIvwk girl models free
sgouZtywwkoHKaFvOt | Feb 14, 2010 | Reply
wkHZYk asian models pictures
eEnAwk girl models free
sex | Mar 12, 2010 | Reply
canlı vıdeolar fragmanlar
lipovSK | Apr 22, 2010 | Reply
Доброе время суток.
Куплю ru траф (дорого), кроме адалт и гэмблинг. За подробностями в личку или на почту [email protected]
Сори ели не туда запостил.
kxOfzvoRwyorcyVTyF | Apr 22, 2010 | Reply
wyZPyN watch filipina babes
oioswy ladies mother fucking
xTeZEUfswytCeuGTig | Apr 22, 2010 | Reply
wyxfIk watch filipina babes
SDEwwy ladies mother fucking
euZtEXZEwySXYueHde | Apr 27, 2010 | Reply
wyESKA watch filipina babes
Lzyewy ladies mother fucking
xiao | Apr 30, 2010 | Reply
Bienvenue à la moins chèrewow gold site web
tSeEpLeJwyVwyXMuEG | May 1, 2010 | Reply
wyDnYI watch filipina babes
wxivwy ladies mother fucking
Bob | May 13, 2010 | Reply
Useful post!
Thank you for sharing with us!
Tony | May 20, 2010 | Reply
I love your post!
Mahero | May 22, 2010 | Reply
Athenes in a conversion from Greek are medium “the goddess of acuteness» – shallow burgh of surprising beauty with which all lot of the Greece ,which has endured the periods of blossoming and drop down, greatness and ignominy is connected.
The Greek islands are known all throughout the world. Island Crete the biggest archipelago of Greece.
Anonymous | Jun 8, 2010 | Reply
http://dehoc123.blogspot.com/
cheers | Jun 11, 2010 | Reply
Jersey has sophisticated seaside hotels and great-value guest houses. We’ve a dash of continental Europe, and a splash of Britain. You’ll find cosmopolitan city life, leafy country lanes, traditional beach cafés and trendy restaurants. Fabulous seafood and fields full of Jersey cows…
vignesh | Aug 11, 2010 | Reply
this is my college project , thankyou for this code
chityonline | Aug 17, 2010 | Reply
Garcia all look at this:
perfect world chity, tanki online krystali chiti
Order Imipramine | Aug 19, 2010 | Reply
Order Imipramine
Cameron Weber | Sep 15, 2010 | Reply
Great blog full of a variety of different guys! Check out more at..
Cam
http://www.icguys.com
http://www.camguys.net
http://www.camwithhim.com
проститутку | Sep 24, 2010 | Reply
Секс это всегда приятно и полезно. Без секса человек становится не адекватен. Индивидуалки москвы всегда готовы прийти на помощь. Конечно не за бесплатно, но зато качественно.
Так же как и проститутки питера. Которые тоже хорошо умеют доставлять удовольствие.
проститутку | Sep 24, 2010 | Reply
Секс это всегда приятно и полезно. Без секса человек становится не адекватен. Индивидуалки москвы всегда готовы прийти на помощь. Конечно не за бесплатно, но зато качественно.
Так же как и проститутки питера. Которые тоже хорошо умеют доставлять удовольствие.
Secure Wireless Internet | Oct 4, 2010 | Reply
This code is a great example for multithreading. Thanks for the informative post — I’ll be sure to check back for all future updates.
buggsbunny29 | Oct 15, 2010 | Reply
WOW! Your posts are real useful. I am trying to learn Java and your information is helping me out. Keep up the great work man. As central processing units these days seem to get more and more cores with each new generation, learning how to optimize a code so that it is multithread compatible is vital in many cases.
Danielle Lovey Grant, of Las Vegas is A RAPIST | Oct 18, 2010 | Reply
Danielle Lovey Grant 23, of Las Vegas is a RAPIST, she and another man used a date rape drug on Victom at 2900 El Camino ave. apt 170, Danielle L Grant sodomized the victim with a plunger, Intestines were hanging out of rectum of victom.She is lite skinned 4 ’9 to 4’11 and she drives a black ford Focus, She works as an dental assistant during day. .STOP her please. Victom is too ashamed to go to police, Danielle L Grant MUST BE STOPED her last know ph # 702-685-9588
El Camino apt 170 Danielle Lovey Grant sodomized the victim with a plunger,Her Discription She is lite skinned mixed women 4 ’7 to 4”9 and she drives a black ford Focus, She works as an dental assistant during day.STOP her Please. HER LADanielle L Grant 23, of Las Vegas is a RAPIST, she and another man used a date rape drug on Victom at 2900 El Camino ave. apt 170, Danielle L Grant sodomized the victim with a plunger, Intestines were hanging out of rectum of victom. She is lite skinned 4 ’9 to 4’11 and she drives a black ford Focus, She works as an dental assistant during day. Sometimes Las Vegas Escort/ Prostitute .STOP her please. Victum is too ashamed to go to police, Danielle L Grant MUST BE STOPED, Known Drug Addict, and Drug Dealer. her last know ph # 702-685-9588
Unicorn Apparels | Oct 21, 2010 | Reply
Thanks for the wonderful example. Very clear
toourok | Oct 26, 2010 | Reply
В интернете Вы можете http://vkontaktelubly.ucoz.ru/ окончательно свободно создать частный бизнес и развить его с нуля, либо перенести уже существующий. Для вашего дела откроются новые горизонты, новые покупатели или потребители. Границ для развития и привлечения новых клиентов в cobweb нет. Обычно, люди имеющие бизнес в интернете получив прибавление с который либо сделки выделяют % в дальнейшую рекламу – продвижение своих услуг или товаров. Данная деятельность ведет к постоянному заработку, постоянному развитию своего бизнеса в web. Ежедневный куш – заклад “завтрашнего дня”.
ICQ 635987774
barber Toronto | Jan 16, 2011 | Reply
Thanks for the info! Your article is very useful specially to those people who wants to be a programmer like me. Those are great guidelines and codes. I also wanna learn how to use Java. Looking forward to read more of your blogs!
biker_the_best | Jan 17, 2011 | Reply
Привет!
Любителям железных коней: лушая мотоэкипировка от ведущих американских производителей.
Доступные цены и быстрая доставка можно найти на на этом сайте – [url=http://mybikershop.com.ua/]мотоэкипировка[/url]. На сайте можно купить или заказать любую позицию из нашего каталога, в котором уже более 12000 позиций.
В каталоге магазина присутствуют мотошлемы и прочная мотоэкипировка от ведущих американских производителей.
engeday | Feb 18, 2011 | Reply
[url=http://000site.ru/go.php?sid=9][img]http://classsex.ru/sex/315.jpg[/img][/url]
[url=http://000site.ru/go.php?sid=9][img]http://opapizda.com/img/17/index.jpg[/img][/url]
[url=http://000site.ru/go.php?sid=9][img]http://tdq.in/images/1/181.jpg[/img][/url]
смотреть порно tv
секс комикс монстры
монологи вагины отзыв
порно 60 летних
секс дедушек
порно секс лошади
купить порно
порно фото 40 женщин
первое занятие сексом
порно фото анны курниковой
[url=http://good-fcmpj.8play.info/]Секс Маструбация[/url]
[url=http://220-minet.8play.info/video-porno-video.html]Порно Видео Целки[/url]
[url=http://odqzec-streem.8play.info/]Vipmodels Секс[/url]
[url=http://wrong-416.8play.info/tag1.html]Поцелуй Секс[/url]
[url=http://sun-stfqm.8play.info/video-ebal-muja.html]Ебал Мужа[/url]
[url=http://ugtuza-191.8play.info/]Главная[/url]
[url=http://fuicef-net.8play.info/blog-sex-reply.html]Sex Reply Php Tname[/url]
[url=http://star-469.8play.info/]Главная[/url]
[url=http://phpbb.8play.info/dlinnyi-porno-lqp.html]Длинный Порно Ролик[/url]
[url=http://blondes-810.8play.info/]Порно Видео Porno[/url]
[url=http://year-live.8play.info/video-yaponskie-foto.html]Японские Фото Эротика[/url]
[url=http://ybflw.8play.info/video-seks-oboi.html]Секс Обой[/url]
[url=http://pornuha-studentka.online-8.info/tag3.html]Порно Разделы[/url]
[url=http://ily-volosatie.online-8.info/blog-porno-smotret.html]Порно Смотреть[/url]
[url=http://porn-651.online-8.info/]Главная[/url]
[url=http://anything-astu.online-8.info/page1.html]Просмотреть Порно[/url]
[url=http://118-your.online-8.info/kuraga-seks-rnr.html]Курага Секс[/url]
[url=http://jpag-incest.online-8.info/]Уфа Секс Знакомства[/url]
[url=http://agqkv.8play.info/zheskoe-porno-z.html]Жёское Порно[/url]
[url=http://tape-eadx.8play.info/erotik-massaj.html]Эротик Массаж[/url]
[url=http://bzyji-668.8play.info/sait-porno-p.html]Сайт Порно Видео[/url]
[url=http://seen-195.8play.info/blog-elena-savina.html]Елена Савина Порно[/url]
[url=http://empuj-831.8play.info/page4.html]Видeо Порно[/url]
[url=http://least-1.online-8.info/porno-sait-mujchin.html]Порно Сайт Мужчин[/url]
[url=http://www.online-8.info/blog-porno-film.html]Порно Фильм Мастурбация[/url]
[url=http://shallow-flv.online-8.info/]Главная[/url]
[url=http://nwfmd.online-8.info/tag2.html]Раздели Телку[/url]
[url=http://736-girl.online-8.info/blog-www-kiev.html]Www Kiev Sex[/url]
[url=http://large.online-8.info/]Главная[/url]
[url=http://bb3-art.online-8.info/plyaj-siski.html]Пляж Сиськи[/url]
[url=http://gmcgpd-streem.online-8.info/tag5.html]Besplatnoe Porno Com[/url]
[url=http://137-many.online-8.info/]Разврат Порно[/url]
[url=http://every.online-8.info/tag1.html]Секс Тест 3 Поросенка[/url]
[url=http://blow-rsizrp.online-8.info/]Главная[/url]
[url=http://eis-personal.online-8.info/page5.html]Порно Сюжет[/url]
[url=http://674-sun.online-8.info/blog-literatura-erotika.html]Литература Эротика Секс[/url]
[url=http://jfoikz.online-8.info/page5.html]Порно Фото Женщины 45[/url]
камасутра способы орального секса
чеченское порновидео
толстушки секси
маленькие porno
правила орального секса
секс фото сквиртинг
mail ru секс
sex video xxx free
секси ирина слуцкая
видео порнуха халява
порно дженнифер лопес
лесбийский секс
веб порно
подростковое порно видео ролики
порно большие губы
веб камера секс желания
пермь порно
братск девушки секс