Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Multithreaded Programming

Java Multithreaded Programming

Java provides built-in support for multithreaded programming. A thread is a single sequential flow of control within a process, and a process can have multiple threads executing concurrently, with each thread running different tasks in parallel.

Multithreading is a special form of multitasking, but multithreading uses smaller resource overhead.

Here is another term related to threads — process: a process includes memory space allocated by the operating system and contains one or more threads. A thread cannot exist independently; it must be part of a process. A process keeps running until all non-daemon threads have finished running.

Multithreading enables programmers to write efficient programs to make full use of the CPU.


Life cycle of a thread

A thread is a dynamic execution process that also has a process from birth to death.

The following diagram shows the complete life cycle of a thread.

-

Wait blocking: A thread in the running state executes the wait() method, causing the thread to enter the wait-blocked state.

-

Synchronous blocking: A thread fails to acquire the synchronized lock (because it is occupied by another thread).

-

Other blocking: When a thread issues an I/O request by calling its sleep() or join(), it enters the blocked state. When sleep() times out, join() waits for the thread to terminate or times out, or I/O processing completes, the thread transitions back to the ready state.


Thread priority

Every Java thread has a priority, which helps the operating system determine the scheduling order of threads.

The priority of a Java thread is an integer ranging from 1 (Thread.MIN_PRIORITY) to 10 (Thread.MAX_PRIORITY).

By default, each thread is assigned a priority of NORM_PRIORITY (5).

Threads with higher priority are more important to the program and should be allocated processor resources before lower-priority threads. However, thread priority does not guarantee the order of thread execution and is highly platform-dependent.


Creating a thread

Java provides three ways to create threads:


Creating a thread by implementing the Runnable interface

The simplest way to create a thread is to create a class that implements the Runnable interface.

To implement Runnable, a class only needs to execute a method call run(), declared as follows:

public

void

run

(

)

You can override this method; it is important to understand that run() can call other methods, use other classes, and declare variables just like the main thread.

After creating a class that implements the Runnable interface, you can instantiate a thread object within the class.

Thread defines several constructors; the following one is the one we commonly use:

Thread

(

Runnable

threadOb

,

String

threadName

)

;

Here, threadOb is an instance of a class that implements the Runnable interface, and threadName specifies the name of the new thread.

After the new thread is created, it will run only when you call its start() method.

void

start

(

)

;

The following is an example of creating a thread and starting its execution:

Example

class

RunnableDemo

implements

Runnable

{

private

Thread

t

;

private

String

threadName

;

RunnableDemo

(

String

name

)

{

threadName

=

name

;

System

.

out

.

println

(

"

Creating

"

threadName

)

;

}

public

void

run

(

)

{

System

.

out

.

println

(

"

Running

"

threadName

)

;

try

{

for

(

int

i

=

4

;

i

0

;

i

--

)

{

System

.

out

.

println

(

"

Thread:

"

threadName

"

,

"

i

)

;

//

Let the thread sleep for a while

Thread

.

sleep

(

50

)

;

}

}

catch

(

InterruptedException

e

)

{

System

.

out

.

println

(

"

Thread

"

threadName

"

interrupted.

"

)

;

}

System

.

out

.

println

(

"

Thread

"

threadName

"

exiting.

"

)

;

}

public

void

start

(

)

{

System

.

out

.

println

(

"

Starting

"

threadName

)

;

if

(

t

==

null

)

{

t

=

new

Thread

(

this

,

threadName

)

;

t

.

start

(

)

;

}

}

}

public

class

TestThread

{

public

static

void

main

(

String

args

[

]

)

{

RunnableDemo

R1

=

new

RunnableDemo

(

"

Thread-1

"

)

;

R1

.

start

(

)

;

RunnableDemo

R2

=

new

RunnableDemo

(

"

Thread-2

"

)

;

R2

.

start

(

)

;

}

}

The result of compiling and running the above program is as follows:


Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Creating a thread by extending Thread

The second way to create a thread is to create a new class that extends the Thread class, and then create an instance of that class.

The inheriting class must override the run() method, which is the entry point of the new thread. It must also call the start() method to execute.

Although this approach is listed as a multithreading implementation, it is essentially also an instance that implements the Runnable interface.

Example

class

ThreadDemo

extends

Thread

{

private

Thread

t

;

private

String

threadName

;

ThreadDemo

(

String

name

)

{

threadName

=

name

;

System

.

out

.

println

(

"

Creating

"

threadName

)

;

}

public

void

run

(

)

{

System

.

out

.

println

(

"

Running

"

threadName

)

;

try

{

for

(

int

i

=

4

;

i

0

;

i

--

)

{

System

.

out

.

println

(

"

Thread:

"

threadName

"

,

"

i

)

;

//

Let the thread sleep for a while

Thread

.

sleep

(

50

)

;

}

}

catch

(

InterruptedException

e

)

{

System

.

out

.

println

(

"

Thread

"

threadName

"

interrupted.

"

)

;

}

System

.

out

.

println

(

"

Thread

"

threadName

"

exiting.

"

)

;

}

public

void

start

(

)

{

System

.

out

.

println

(

"

Starting

"

threadName

)

;

if

(

t

==

null

)

{

t

=

new

Thread

(

this

,

threadName

)

;

t

.

start

(

)

;

}

}

}

public

class

TestThread

{

public

static

void

main

(

String

args

[

]

)

{

ThreadDemo

T1

=

new

ThreadDemo

(

"

Thread-1

"

)

;

T1

.

start

(

)

;

ThreadDemo

T2

=

new

ThreadDemo

(

"

Thread-2

"

)

;

T2

.

start

(

)

;

}

}

The result of compiling and running the above program is as follows:


Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Thread methods

The following table lists some important methods of the Thread class:

No. Method Description
1 public void start()
Causes this thread to begin execution;Java the virtual machine calls the thread's run method.
2 public void run()
If this thread was constructed using a separate Runnable run object, then the run method of that Runnable object is called; otherwise, this method does nothing and returns.
3 public final void setName(String name)
Changes the thread name to be the same as the parameter name.
4 public final void setPriority(int priority)
 Changes the priority of the thread.
5 public final void setDaemon(boolean on)
Marks this thread as a daemon thread or a user thread.
6 public final void join(long millisec)
Waits for this thread to terminate for at most millis milliseconds.
7 public void interrupt()
Interrupts the thread.
8 public final boolean isAlive()
Tests whether the thread is active.

The methods above are called on Thread objects; the methods in the table below are static methods of the Thread class.

No. Method Description
1 public static void yield()
Suspends the currently executing thread object and executes other threads.
2 public static void sleep(long millisec)
Causes the currently executing thread to sleep (suspend execution) for the specified number of milliseconds; this operation is subject to the precision and accuracy of the system timer and scheduler.
3 public static boolean holdsLock(Object x)
Returns true if and only if the current thread holds the monitor lock on the specified object.
4 public static Thread currentThread()
Returns a reference to the currently executing thread object.
5 public static void dumpStack()
Prints the stack trace of the current thread to the standard error stream.

Example

The following ThreadClassDemo program demonstrates some methods of the Thread class:

DisplayMessage.java file code:

//

File name: DisplayMessage.java

//

Create a thread by implementing the Runnable interface

public

class

DisplayMessage

implements

Runnable

{

private

String

message

;

public

DisplayMessage

(

String

message

)

{

this

.

message

=

message

;

}

public

void

run

(

)

{

while

(

true

)

{

System

.

out

.

println

(

message

)

;

}

}

}

GuessANumber.java file code:

//

File name: GuessANumber.java

//

Create a thread by extending the Thread class

public

class

GuessANumber

extends

Thread

{

private

int

number

;

public

GuessANumber

(

int

number

)

{

this

.

number

=

number

;

}

public

void

run

(

)

{

int

counter

=

0

;

int

guess

=

0

;

do

{

guess

=

(

int

)

(

Math

.

random

(

)

100

1

)

;

System

.

out

.

println

(

this

.

getName

(

)

"

guesses

"

guess

)

;

counter

++;

}

while

(

guess

!=

number

)

;

System

.

out

.

println

(

"

** Correct!

"

this

.

getName

(

)

"

in

"

counter

"

guesses.**

"

)

;

}

}

ThreadClassDemo.java file code:

//

File name: ThreadClassDemo.java

public

class

ThreadClassDemo

{

public

static

void

main

(

String

[

]

args

)

{

Runnable

hello

=

new

DisplayMessage

(

"

Hello

"

)

;

Thread

thread1

=

new

Thread

(

hello

)

;

thread1

.

setDaemon

(

true

)

;

thread1

.

setName

(

"

hello

"

)

;

System

.

out

.

println

(

"

Starting hello thread...

"

)

;

thread1

.

start

(

)

;

Runnable

bye

=

new

DisplayMessage

(

"

Goodbye

"

)

;

Thread

thread2

=

new

Thread

(

bye

)

;

thread2

.

setPriority

(

Thread

.

MIN_PRIORITY

)

;

thread2

.

setDaemon

(

true

)

;

System

.

out

.

println

(

"

Starting goodbye thread...

"

)

;

thread2

.

start

(

)

;

System

.

out

.

println

(

"

Starting thread3...

"

)

;

Thread

thread3

=

new

GuessANumber

(

27

)

;

thread3

.

start

(

)

;

try

{

thread3

.

join

(

)

;

}

catch

(

InterruptedException

e

)

{

System

.

out

.

println

(

"

Thread interrupted.

"

)

;

}

System

.

out

.

println

(

"

Starting thread4...

"

)

;

Thread

thread4

=

new

GuessANumber

(

75

)

;

thread4

.

start

(

)

;

System

.

out

.

println

(

"

main() is ending...

"

)

;

}

}

The running result is as follows; each run produces a different result.


Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......

Creating a thread with Callable and Future

Example

public

class

CallableThreadTest

implements

Callable

<

Integer

{

public

static

void

main

(

String

[

]

args

)

{

CallableThreadTest

ctt

=

new

CallableThreadTest

(

)

;

FutureTask

<

Integer

ft

=

new

FutureTask

<>

(

ctt

)

;

for

(

int

i

=

0

;

i

<

100

;

i

++

)

{

System

.

out

.

println

(

Thread

.

currentThread

(

)

.

getName

(

)

"

The value of loop variable i

"

i

)

;

if

(

i

==

20

)

{

new

Thread

(

ft

,

"

Thread with a return value

"

)

.

start

(

)

;

}

}

try

{

System

.

out

.

println

(

"

Return value of the child thread:

"

ft

.

get

(

)

)

;

}

catch

(

InterruptedException

e

)

{

e

.

printStackTrace

(

)

;

}

catch

(

ExecutionException

e

)

{

e

.

printStackTrace

(

)

;

}

}

@

Override

public

Integer

call

(

)

throws

Exception

{

int

i

=

0

;

for

(

;

i

<

100

;

i

++

)

{

System

.

out

.

println

(

Thread

.

currentThread

(

)

.

getName

(

)

"

"

i

)

;

}

return

i

;

}

}


Comparison of the three ways to create threads


Several main concepts of threads

When programming with multiple threads, you need to understand the following concepts:


Use of multithreading

The key to effectively using multithreading is understanding that programs execute concurrently rather than serially. For example: if a program has two subsystems that need to execute concurrently, multithreaded programming is needed.

By using multithreading, you can write very efficient programs. However, note that if you create too many threads, the efficiency of program execution actually decreases rather than improves.

Please remember that the overhead of context switching is also significant; if you create too many threads, the CPU will spend more time on context switching than on executing the program!