You are on page 1of 16

Threads


(process)

(
)


(thread)

(, ,
)
( )

(tasks),
( )
,


:

(process

control block)
(address space)

context-switching
context-

switching

Java
:
java.lang.Thread:


java.lang.Runnable:

run,
run Runnable,
Thread ( Thread
Runnable)
6

Thread
Thread
public class ExampleThread extends Thread
{
public void run()
{
// perform whatever thread needs to do
}
}

thread
ExampleThread et = new ExampleThread();
et.start();

start() Thread

Runnable

Runnable interface
public class ExampleRunnable implements Runnable
{
public void run()
{
// perform whatever thread needs to do
}
}

thread
ExampleRunnable er = new ExampleRunnable();
new Thread(er).start();


start()
leaving non-runnable
Ready to Run
scheduling

timeslice
ends
Running

entering
non-runnable

Non-runnable states
Waiting

terminates
Dead

Sleeping

Blocked

10



stack space,
heap (
)
:

11

Monitor:

( )
monitor ( semaphore)

monitor
monitor

monitors
( mutex)

(race conditions)
(race condition)



,
(

)

,

(race conditions)


H Java

( )
synchronized

( )
:
public synchronized void xmethod {}
xmethod

(blocked)

( ):

15

public int ymethod {


...
synchronized (this) {
...
}
}

(Deadlocks)

,

(deadlock)
Java

16

You might also like