Understanding Multithreading in Java

Java provides built in support for multithreaded programming. A Multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a Thread. Each thread defines a separate path of execution. Multithreading is a specialized form of Multitasking.

Multitasking is divided into two types. They are

(1) Process based: Here two or more programs runs concurrently. You can run Windows calculator and a Text editor (Notepad) at the same time.

(2) Thread based: A single program can perform two or more tasks simultaneously. For example, text editor can print while formatting is being done.

Multithreading enables you to write very efficient programs that make maximum use of CPU, because idle time can be kept to minimum. This is especially important for the interactive networked application because idle time is common. In a traditional single threaded environment, your program has to wait for each of the tasks to finish before it can proceed to the next one. This will result in idle time. Multithreading lets you gain access to this idle time and put it to good use.

Java’s Model of Thread

One thread can pause without stopping other parts of your Program. Multithreading allows animation loops to sleep for a second between each frame without causing the whole system to pause. When a thread blocks in a java program, only the single thread that is blocked pauses. All other threads continue to run.

Also note the following points regarding threads.

(1) A thread can be running. It can be ready to run as soon as it begins execution
(2) A running thread can be suspended which temporarily suspends its activity
(3) A suspended thread can be resumed
(4) A thread can be blocked when waiting for a resource. (sleeps for a while)

READ  Introducing ASP.NET

At any time a thread can be terminated, which means the thread stops. Once stopped it cannot be resumed.

Thread priorities

Thread priorities are integers that specify the relative priority of one thread to another. Higher priority thread doesn’t run any faster than a lower priority thread. Instead a thread’s priority is used to decide when to switch from one running thread to the next This is called as context switch. A thread can have a maximum priority of 10 and a minimum of 1. Normal Priority is 5.

Thread class Methods

start() –> Starts execution of the thread.
stop() –> Terminates the current thread.
suspend() –> Suspends the thread.
resume() –> Restarts the suspended thread.
sleep() –> This method suspends execution of the executing thread for the specified number of milliseconds. It can throw an interrupted Exception.

getName() –> Obtains a thread name.
getPriority() –> Obtain a thread’s priority.
Isalive() –> Determine if a thread is still running.
wait() –> Waits for a thread to terminate.
run() –> Entry point for the Thread.

When a java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is the one that is executed when your program begins. Main thread will be the last thread to finish execution. When the main thread stops
your program terminates.

Creation of a thread

You can create a thread in one of the following ways

(1) You can implement the Runnable Interface and apply its run() method.

(2) You can extend the Thread class itself.

(1) Implementing Runnable Interface: The easiest way to create a thread is to create a class that implements the Runnable interface. To implement Runnable, a class need only implement a single method called run(). The Format of that function is public void run().

READ  Understanding Access Specifiers in Java

2. Extending Thread: The second way to create a thread is to create a new class that extends the Thread class and then to create an instance of this class. This class must override the run() method which is the entry point for the new thread.

Synchronization in Java

1. Two or more threads accessing the same data simultaneously may lead to loss of data integrity. In order to avoid this java uses the concept of monitor. A monitor is an object used as a mutually exclusive lock.

2. At a time only one thread can access the Monitor. A second thread cannot enter the monitor until the first comes out. Till such time the other thread is said to be waiting.

3. The keyword Synchronized is use in the code to enable synchronization and it can be used along with a method.

Inter Thread Communication

There may be cases where one of the created threads require data from another thread. Java achieves this through the usage of wait(), notify(), notifyAll() methods of the object class.

wait() –> This method waits indefinitely until it receives a notification
notify() –> This wakes up a single thread waiting on the objects monitor.
notifyAll() –> This wakes up all the threads waiting on the objects monitor.

30 Responses to "Understanding Multithreading in Java"

  1. RerbPremexpek   January 5, 2010 at 8:02 am

    HI, there:
    I bought a Dell Laptop with windows 7 home premium a month ago and I reinstalled the system with the windows 7 DVD came with the Laptop. However I don’t know I need to activate the windows 7 at that time.
    Now after 30 days, I have a problem that, the windows message says that, my activation period has been expired. Even when I tried to input the product key on the Dell laptop, it is said that the product key is invalid.
    Would you please tell me what to do except reinstalling the windows 7 if reinstallation can solve this problem.

  2. aloforBiono   March 15, 2010 at 8:32 am

    I did not think I would ever say this, but I am glad to be home. org LawrenceDavid for other stories and to contact me.

    sex position furniture
    sex positions

    virg Virgin should be 1st. 1st attachment end ASSM Moderation System Notice Notice This post has been modified from its originalformat.

    sex positions doggy style
    illustrated sex positions guide

    said Sabrina, triumphantly. V.

    man women sex positions
    crab sex position

    Asshe passed the grandee she girlishly stuck her tongue out at Tiffany. I was falling then, or more like weightless maybe, with my hotblood rushing all through me as I came hard.

    guy on top sex positions
    missionary position sex videos

    Show time is 8 oclock. Upstairs was one big room with theexception of a small bathroom in one corner.

  3. hathgeatt   April 2, 2010 at 9:38 pm


    Access TV Station Channels Worldwide Satellite Tv connection hack site

    However, the satellite TV for PC programs below are superior to cable TV and satellite TV service, and include the following benefits:

    * Free lifetime software updates
    * Satellite TV Feeds on PC works with Windows®, Mac and Linux OS systems
    * No viruses, malware, spyware, adware, hacking or cracking included
    * Watch TV online anytime, anywhere, anyplace, 24 hours, 7 days
    * Works with 56k modem (dial-up) and high speed internet (DSL, cable, T1, wireless, satellite, etc.)
    * Free lifetime software updates
    * Payments accepted: – with secure 128-bit SSL encryption
    * One time fee with lifetime unlimited access to all channels

    Begin Watching TV Online Now via… Digital TV website

  4. stessY   July 23, 2010 at 6:53 pm

    !!! PORNO !!!

    http://harizzzma.com/pornpics/an82.jpg http://harizzzma.com/pornpics/an176.jpg
    http://harizzzma.com/pornpics/an7.jpg http://harizzzma.com/pornpics/an198.jpg
    http://harizzzma.com/pornpics/an12.jpg http://harizzzma.com/pornpics/an109.jpg

    !!! ENTER !!!

    секси медсестра
    секс ярославль
    проститутки порно групповой секс
    фотки пиписьки
    видео порно скачивание безплатно

    Ролики Порнуха Webhome New Topic
    Рейтинг Порнофильмов
    Девушка Лежит Голая
    Посмотреть Порно Без Скачки
    Посмотреть Порно Через Интернет
    Анальный Полип
    Порно Видео Просмотор
    Фото Красивых Голых Мужчин
    Порно Мультфильмы 3d Комиксы
    Азиатки Порно Yabb
    Порно Зрелые 40
    Анальный Секс После Родов
    Просмотр Порно Видио
    Азиатки Школьницы Порно
    Секс Видео Анфисы Чеховой
    Лесби Чат Общение Без Регистрации
    Чертик Порно Девочки
    Голые Пожилые Женщины
    Геи Пермь
    Видио Про Секс
    Лучшее Порно Со Знаменитостями
    Интересные Девушки
    Заказать Dvd Порно
    Обои Эротика Порно
    Износилование Жестокий Секс Видео
    Гей Порно Фото Видео
    Брюнетки Лесбиянки Онлайн
    Фото Влагалища Целки
    Девочка Лижет Писю
    Порно Фото Голых Жоп
    Скачать Порно Износилования
    Мастурбация Зависимость
    Голое Порно Красивых Девушек
    Порно Клипы Знаменитостей
    Немецкий Порно Сайты Ip Logged
    Секс Сайт
    Смотреть Порно Оргазм
    Порно Смс Малолетки
    Эротика Парнуха
    Молодежное Порно Извращения
    Мастурбация Телефоном Видео
    Анал Sex Phpbb
    Мама Лезбиянка
    Просмотреть Порно Видео Send Message
    Бритни Спирс Видео Порно Скачать
    Книги Секс
    Порно Рассказы Попку
    Порно Секс Оргии
    Bdsm Бондаж
    Смотреть Порно Лесбиянок Без Смс
    Порнозвезды Большие Сиськи
    Порно Просмотреть Видео Скачать
    Ipb Жопа
    Красивые Голые Девочки Фото
    Блондинка За Рулем Видео
    Красивое Лесби

    секс сайты смоленска
    секс сексуальное видео
    порно видео пожелые
    порно секс миньет
    галерея фото порнухи
    сайт любителей группового секса
    секс дед мороз
    making porno
    секс извращения
    безплатное порно без
    обучение технике секса
    подборка писек
    личное секс фото
    памела андерсен видео порно
    тинэйджеры секс
    sex forum php
    подольск порно
    ласковый секс
    секс сон
    порно бриана бэнкс


Leave a Reply

Your email address will not be published.