A process is an execution of a program but a thread is a
single execution sequence within the process.
A process has its own memory space, and can contain
multiple threads. Thread share the
resource belongs to the process.
Difference ways to create thread
1, implement the runnable interface, and need to create
an Thread Object and pass the runnable instance.
public void example1 implements Runnable{
public void run(){
}
}
public static void main(String[] args){
example1
instance = new example1();
Thread
thread = new Thread(instance);
thread.start();
}
2, extents the Thread class.
public void example2 extends Thread{
public void run(){
}
}
public static void main(String[] args){
example2
instance = new example2();
instance.start();
}
Extending Thread Class vs. Implementing the Runnable Interface
Implementing the Runnable Interface may be preferable:
1) Java does
support multiple inheritance, once you extends Thread class, the subclass can
not extend any other class.
2) A class might only be interested in being runnable,
and therefore, inheriting the full overhead of the Thread class would be
excessive.
Thread yield, wait, sleep
wait: current
thread to wait until another thread invokes the notify() method.
Yield: A suggestion to the thread scheduler that this would be a good time to switch to another task for a while.
Sleep: block the execution of that task for a given time. Do not release the object lock.
Deadlock
Threads within a given process share the same memory space.
For conditions of deadlock
Deadlock
Threads within a given process share the same memory space.
Deadlock is situation that a thread is waiting for an object
lock that another thread holds, and this second thread is waiting for another
object lock that the first thread holds. So both of them remain waiting
forever.
For conditions of deadlock
1, Mutual Exclusion:
Only one process can access a resource at a given time.
2, Hold and Wait: Thread already holding a resource can
request additional resources.
3, No Preemption: One thread can’t remove others’ resources.
4, Circular Wait: Form a chain, each thread is waiting on
another’s resource in the chain.
Thread States
1. New : allocates any necessary system resources and performs initialization.
Thread States
1. New : allocates any necessary system resources and performs initialization.
2. Runnable: The scheduler can arrange it.
3. Blocked: The thread can be run, but something prevents it. The schedule will simply skip it and not give it any CPU time.
- the task is put to sleep()
- the execution is suspended with wait()
- waiting for some I/O to complete
- trying to call synchronized method on an object, whose lock is not available.
4. Dead: return from run() or be interrupted. Will not receive any CPU time.
No comments:
Post a Comment