Friday, July 11, 2014

Java多线程入门(一) 基本概念

这几天自学了下JAVA的多线程,打算把一些入门的知识总结一下。水平有限,写的比较乱。

Process vs Thread

  • process: program / application, has its own memory space, stack, heap and other os resources. not share memory space with other process
  • thread: one process can have multi threads. A thread is the fundamental unit of execution. Each thread has its own stack, but can access shared data of other threads in the same process.
  • A Java application runs by default in one process.

实现多线程的两种方法

1)使用Runnable接口
public class RunnableExample implements Runnable{  
      @Override  
      public void run() {  
           // TODO Auto-generated method stub  
           System.out.print("Hello World");  
      }  
        
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           RunnableExample test = new RunnableExample();  
           Thread thread = new Thread(test);  
           thread.start();  
      }  
} 
2)继承Thread类
public class ThreadExample extends Thread{  
      @Override  
      public void run() {  
           // TODO Auto-generated method stub  
           System.out.print("Hello World");  
      }  
        
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           Thread thread = new ThreadExample();  
           thread.start();  
      }  
}  
我们发现两者必须都实现run()这个method。对于使用Runnable来说,我们必须先生成一个object后用它来生成一个thread,但是对于继承Thread,我们可以直接用这个object进行thread的操作。
一般来说用Runnable比较好。因为JAVA是单继承语言,对于一个子类不能有多个父类,继承了Thread类后就无法继承其他类了。

Race Condition: A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.

Critical Section: a piece of codes that access and modify the shared state.

Mutual Exclusion: at any time, only one thread can access or modify the shared state with the critical section code.

An interrupt is an indication to a thread that it should stop what it is doing and do something else.

DeadLock, Starvation, LiveLock

DeadLock: a situation where two or more threads are blocked forever, waiting for each other. 

Starvation: describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads.

LiveLock: A thread often acts in response to the action of another thread. If the other thread's action is also a response to the action of another thread, then livelock may result. As with deadlock, livelocked threads are unable to make further progress. However, the threads are not blocked — they are simply too busy responding to each other to resume work. 

DeadLock(four conditions):
1. mutual exclusion
2. hold and wait
3. no preemption: The operating system must not de-allocate resources once they have been allocated; they must be released by the holding process voluntarily.
4. circular wait

Sleep, Wait

sleep() is a method which is used to hold the process for few seconds or the time you wanted but in case of wait() method thread goes in waiting state and it won’t come back automatically until we call the notify() or notifyAll().
The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases any lock or monitor while waiting.

Semaphore vs Mutex

Semaphores which allow an arbitrary resource count are called counting semaphores, while semaphores which are restricted to the values 0 and 1 (or locked/unlocked, unavailable/available) are called binary semaphores.

  1. Mutexes have a concept of an owner, which is the process that locked the mutex. Only the process that locked the mutex can unlock it. In contrast, a semaphore has no concept of an owner. Any process can unlock a semaphore.
  2. Unlike semaphores, mutexes provide priority inversion safety. Since the mutex knows its current owner, it is possible to promote the priority of the owner whenever a higher-priority task starts waiting on the mutex.
  3. Mutexes also provide deletion safety, where the process holding the mutex cannot be accidentally deleted. Semaphores do not provide this.

No comments:

Post a Comment