Docsity

Java Threading: Understanding Threads, Creating and Running Them, and Synchronization, Study notes of Javascript programming

Partial preview of the text

Download Java Threading: Understanding Threads, Creating and Running Them, and Synchronization and more Study notes Javascript programming in PDF only on Docsity!

Programming in Java

CSCI 2220Threads

Threads

•^

What is a thread?– A “flow of control” in a program– Up until now, you have written programs that have only one

single flow of control

  • With threads, you can have many flows executing at the same

time

•^

Example: Consider your basic word processor– You have just written a large amount of text and now hit the save

button

  • It probably takes a noticeable amount of time to save the new

data to disk, this is all done with a separate thread in thebackground

  • Without threads, the application would appear to hang while you

are saving the file and be unresponsive until the save operationis complete

Running Threads

•^

Creating an instance of the previous class does notactually create the thread. You must call the start()method of the Thread class

•^

The call to myThread.start() creates a new Thread andschedules the run() method of myThread to execute

•^

myThread.start() returns almost immediately

public class

ThreadExampleMain

public static void

main(String[] args) {

Thread myThread =

new

ThreadExample(“my data”);

myThread.start();System.out.println(“I am the main thread”); } }

The Runnable Interface

•^

There is also a way to create a Thread in Java withoutextending the Thread class

•^

You can implement the Runnable interface instead whichdefines one method: public abstract void run()

•^

This is particularly useful if you wish to create a Thread objectbut want to use a different base class than the Thread class^ public class

RunnableExample

extends

SomeClass

implements

Runnable

private

String data;

public

RunnableExample(String data) { this

.data = data;

} public void

run() {

System.out.println(“I am a thread”);System.out.println(“I was given an argument : “ + data); } }

Thread Scheduling

-^

The JVM chooses which thread to run according to a “fixed priorityalgorithm”

-^

Every thread has a priority between the range ofThread.MIN_PRIORITY and Thread.MAX_PRIORITY

-^

By default a thread is instantiated with the same priority as thethread that created it.

-^

You can change the priority using the setPriority() method of theThread class

-^

Threads with higher priorities are run to completion before Threadswith lower priorities get a chance at CPU time

-^

The algorithm is preemptive, so if a lower priority thread is running,and a higher priority thread becomes runnable, the high prioritythread will pre-empt the lower priority one

Thread Scheduling

-^

If threads with the same priority are waiting to execute, an arbitrarythread will be chosen

-^

Once a thread gains control of the CPU, it will execute until one ofthe following occurs:–

Its run() method exits

-^

A higher priority thread becomes runnable and pre-empts it

-^

Its time slice is up (on a system that supports time clicing)

-^

It calls sleep() or yield()

-^

When a call to yield() is made, the thread gives othre threads withthe same priority a chance to gain the CPU. If no other threads ofthe same priority exist, the thread continues to execute

-^

When a call to sleep() is made, the thread sleeps for the specifiednumber of milliseconds, during which time any other thread can usethe CPU

Other Thread operations

interrupt()

method

– A call to the interrupt() method sets the thread’s status to

interrupted. This does not explicitly interrupt the thread,but this status can be checked from within the thread tofacilitate any type of operation

interrupted()

method

– This method returns a boolean value indicating the

interrupted status of the current thread. A call to thismethod resets the status of the current thread to notinterrupted

•^

The use of these two methods in combination canserve as a method of requesting that a thread yield,sleep, or terminate itself for example

Synchronization

•^

Often times, multiple threads are accessing thesame resources concurrently– Reading and/or writing the same file– Modifying the same object/variable– Etc.

•^

In these cases, you must be careful how youcoordinate these operations so that the resourcesend up in a consistent and expected state

•^

Java has built in primitives to facilitate thiscoordination

Synchronization Example

•^

The Producer thread: public class

Producer

extends

Thread

private

CubbyHole cubbyhole;

private int

number;

public

Producer(CubbyHole c,

int

number) {

cubbyhole = c;this.number = number; } public void

run() {

for

int

i = 0; i < 10; i++) {

cubbyhole.put(number, i); try

{ sleep((int)(Math.random() * 100)); }^

catch

(InterruptedException e) { }

Synchronization Example

•^

The Consumer thread: public class

Consumer

extends

Thread

private

CubbyHole cubbyhole;

private int

number;

public

Consumer(CubbyHole c,

int

number) {

cubbyhole = c;this.number = number; } public void

run() {

int

value = 0; for

(int i = 0; i < 10; i++) {value = cubbyhole.get(number); } } }

Synchronization Example

•^

Solution: synchronization

•^

When a thread executes a synchronized method, itlocks the object of the method that has been called

•^

public class No synchronized methods can be called by anotherthread on that object until the object is unlocked

CubbyHole

private int

contents;

private boolean

available = false;

public synchronized int

get(

int

who)

{ ... } public synchronized void

put(

int

who,

int

value)

Synchronization Example

•^

Synchronized methods stop the producer and consumer frommodifying the CubbyHole at the same time, however, we stillneed to coordinate the producer and consumer threads sothat they do not produce or consume out of order public synchronized int

get() {

while

(available == false) { try

{ //wait for Producer to put value wait(); }^

catch

(InterruptedException e) { }

} available = false;//notify Producer that value has been retrieved notifyAll(); return

contents;

Homework 6

• Homework 6 will be posted on the web

soon

• Due March 30 (3 weeks from now)• Homework 5 due 11:55 PM tonight