Multi-threading programming in Java

来源:互联网 发布:linux多线程理解 编辑:程序博客网 时间:2024/05/17 00:16

Thread: an independent path of execution through program code. is a dispatchable unit of work.

process: is a program in execution. 

process-based multitasking: multitasking of two or more processes, like two applications are run on a computer(MS word, Visual Studio), which is controlled by the OS.

thread-based multitasking: multitasking of two or more threads, can be controlled by the programmer to some extent in a program.


Threads are objects in Java via two different mechanisms:

1. Create a class that extends the standard Thread class. (java.lang.Thread class)

2. Create a class that implements the standard Runnable interface. (java.lang.Runnable interface)


The run() method should be overridden and should contain the code that will be executed by the new thread. public void return with not any argument.

//Using extend Thread class//1. Create a class by extending the Thread class and override the run() methodclass MyThread extends Thread{        public void run(){             //thread body of execution       }} //2. Create a thread objectMyThread thr1 = new MyThread();//3. start execution of created threadthr1.start();



//The steps for creating a thread by using the Runnable interface//1. Create a class that implements the interface Runnable and override run() method.class MyThread implements Runnable{     public void run(){           // thread body of execution     }}//2. creating object:MyThread myObject = new MyThread();//3. creating thread objectThread thr1 = new Thread(myObject);//4. Start Executionthr1.start();

Thread class vs Runnalbe Interface

By extending the thread class, the derived class itself is a thread object and it gains full control over the thread life cycle. 

Implementing the Runnable interface does not give developers any control over the thread itself. as it simply defines the unit of work that will be executed in a thread 

Another important point is that when extending the Thread class, the derived class cannot extend any other base classes. 

By implementing the Runnable interface, the class can still extend other base classes if necessary. 

To summary, if the program needs a full control over the thread life cycle, extending the Thread class is a good choice, and if the program needs more flexibility of extending other base classes, implementing the Runnable interface would be preferable. If none of these is present, either of them is fine to use.

One difference between implementing Runnable and extending Thread is that by extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable,

many threads can share the same object instance.


A class that implements Runnable is not a thread and just a class.For a Runnable to become a Thread, You need to create an instance of Thread and passing itself in as the target.


In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.


When there is a need to extend a superclass, implementing the Runnable interface is more appropriate than using the Thread class. Because we can extend another class while implementing Runnable interface to make a thread. But if we just extend the Thread class we can't inherit from any other class.


Monitor is an object or module intended to be used safely by more than one thread.



Thread life Cycle

NEW: when a start() method is invoked, the thread moves to the ready state from which it is automatically moved to runnable state by the thread scheduler.

Runnable: A thread executing in the JVM is in running state.

Blocked: a thread is blocked waiting for a monitor lock is in this state. This can also occur when a thread performs an I/O operation and moves to next(runnable) state.

Waiting: a thread that is waiting indefinitely for another thread to perform a particular action is in this state.

Timed_waiting(sleeping): is waiting for another thread to perform an action for up to a specified waiting time is in this state.

Terminated(dead): a thread that has exited is in this state.



Thread priority: all the thread instances the developer created have the same priority. We could set priority using the

//set thread priority. //MIN_PRIORITY = 1; NORM_PRIORITY = 5, MAX_PRIORITY = 10;Thread.setPriority();


Thread methods:

sleep() method causes the current thread to sleep for a specified amount of time in milliseconds. 

yield() method causes the current thread to move from the running state to the RUNNABLE state. 

isAlive() method return true if the thread upon which it is called has been started but not moved to the dead state.

join() method, when a thread calls it on aonther thread, the currently running thread will wait until the thread it joins with has completed. It also can set to wait for a limited amount of time

void join();void join(long millis)void join(long millis, int nanos)


Issues:

Read/Write problem: one thread read the data, while another thread tries to update the same data. via synchronizing access to the data

public synchronized void update(){   ...}

Producer/Consumer problem. The two threads, producer and the customer, who share a common, fixed-size buffer. The problem is to make sure that the producer will not try to add data into the buffer if it is full and that the consumer will not try to remove data from an empty buffer. 

The solution for this problem involves two parts. The producer should wait when it tries to put the newly created product into the buffer until there is at least one free slot in the buffer. The consumer, on the other hand, should stop consuming if the buffer is empty. 

Reference:  http://www.buyya.com/java/




0 0