線程的創建#
創建線程有兩種方式:繼承Thread類,或者實現Runnable接口
繼承Thread類##
public class MyThread extends Thread{
public void run(){
System.out.println("MyThread running");
}
}
MyThread myThread = new MyThread();
myThread.start();
也可以創建一個匿名類繼承自Thread
Thread thread = new Thread(){
public void run(){
System.out.println("Thread running");
}
}
thread.start();
實現Runnable接口##
public class MyRunnable implements Runnable{
public void run(){
System.out.println("MyRunnable running");
}
}
Thread myThread = new Thread(new MyRunnable());
myThread.start();
常見錯誤:start()而不是run()##
不管實現Runnable接口還是繼承自Thread類,通過start方法去啟動該線程。如果調用的是run方法,其實是在當前線程執行的。
這可以通過下面的例子驗證
public class MyThread extends Thread{
public void run(){
System.out.println(Thread.currentThread() + ": running 1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread() + ": running 2");
}
public static void main(String[] args) throws InterruptedException {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.run();
thread2.run();
thread1.join();
thread2.join();
}
}
輸出結果是
Thread[main,5,main]: running 1
Thread[main,5,main]: running 2
Thread[main,5,main]: running 1
Thread[main,5,main]: running 2
而如果把run改為start,輸出結果才符合我們的預期
Thread[Thread-0,5,main]: running 1
Thread[Thread-1,5,main]: running 1
Thread[Thread-0,5,main]: running 2
Thread[Thread-1,5,main]: running 2
線程安全#
下圖描述了java內存模型
多線程之間可能會共享變量。當他們同時修改一個共享變量時,就會產生race condition。這時候,可以使用synchronized關鍵字或者Lock避免race condition。
synchronized##
a synchronized block guarantees that only one thread can enter a given critial section. synchronized block also guarantee that all the variables accessed inside the synchronized block will be read in from main memory, and when the thread exists synchronized block, all update variables will be flushed back to main memory again.
synchronized關鍵字可以用來標記四中不同的block。
- instance method
- static method
- code blocks inside instance method
- code blocks inside static method
public class MyClass {
public synchronized void log1(String msg1, String msg2){
log.writeln(msg1);
log.writeln(msg2);
}
public void log2(String msg1, String msg2){
synchronized(this){
log.writeln(msg1);
log.writeln(msg2);
}
}
}
Lock##
Lock其實是用synchronized關鍵字實現的。下面是一個簡單的實現
public class Lock{
private boolean isLocked = false;
public synchronized void lock()
throws InterruptedException{
while(isLocked){
wait();
}
isLocked = true;
}
public synchronized void unlock(){
isLocked = false;
notify();
}
}
java.util.concurrent.Lock包中,Lock是一個接口,有以下幾個方法
- lock()
- lockInterruptibly()
- trylock()
- trylock(long timeout, TimeUnit timeUnit)
- unlock()
實現Lock接口的類有ReentrantLock和ReadWriteLock。
ReentrantLock就是普通的lock。
ReadWriteLock實現了多讀,單寫。
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
readWriteLock.readLock().lock();
// multiple readers can enter this section
// if not locked for writing, and not writers waiting
// to lock for writing.
readWriteLock.readLock().unlock();
readWriteLock.writeLock().lock();
// only one writer can enter this section,
// and only if no threads are currently reading.
readWriteLock.writeLock().unlock()
synchronized和Lock##
synchronized和Lock還是有些區別的:
- 如果有多個線程等待,synchronized block不保證這些線程進入的順序就是他們到達等待的順序
- 因為不能傳遞參數給synchronized block,因此沒法設置timeout時間
- synchronized block必須在一個函數體內。但是lock和unlock可以在不同的函數體內。
線程安全的容器##
java.util.concurrent包里面提供了很多線程安全的容器,可以讓我們在多線程編程的時候更加容易。
- BlockingQueue
- ArrayBlockingQueue
- LinkedBlockingQueue
- DelayQueue
- PriorityBlockingQueue
- SynchronousQueue
- BlockingDeque
- LinkedBlockingDeque
- ConcurrentMap
- ConcurrentNavigableMap
線程安全的類##
多線程使得任何操作都變得如履薄冰。比如,你想對一個int類型的共享變量進行++操作,那么傳統的 i++不是線程安全的。因為這句并不是原子操作。因為java給我們提供了一些原子操作類。
- AtomicBoolean
- AtomicInteger
- AtomicLong
- AtomicReference
- AtomicStampedReference
- AtomicIntegerArray
- AtomicLongArray
- AtomicReferenceArray
線程同步#
wait & notify##
java.lang.Object定義了三個方法 wait(), notify(), notifyAll()。通過這幾個方法,可以讓一個線程等待一個信號,也可以讓另外一個線程發送一個信號。調用了wait()的線程會貶稱inactive狀態,直到另外一個線程調用notify()。
需要注意的是,調用wait或者notify的線程必須要獲得這個對象的鎖。也就是說,一個線程必須在synchronized block中調用wait notify。
public class MonitorObject{
}
public class MyWaitNotify{
MonitorObject myMonitorObject = new MonitorObject();
public void doWait(){
synchronized(myMonitorObject){
try{
myMonitorObject.wait();
} catch(InterruptedException e){...}
}
}
public void doNotify(){
synchronized(myMonitorObject){
myMonitorObject.notify();
}
}
}
Wouldn't the waiting thread keep the lock on the monitor object (myMonitorObject) as long as it is executing inside a synchronized block? Will the waiting thread not block the notifying thread from ever entering the synchronized block in doNotify()? The answer is no. Once a thread calls wait() it releases the lock it holds on the monitor object. This allows other threads to call wait() or notify() too, since these methods must be called from inside a synchronized block.
Once a thread is awakened it cannot exit the wait() call until the thread calling notify() has left its synchronized block. In other words: The awakened thread must reobtain the lock on the monitor object before it can exit the wait() call, because the wait call is nested inside a synchronized block. If multiple threads are awakened using notifyAll() only one awakened thread at a time can exit the wait() method, since each thread must obtain the lock on the monitor object in turn before exiting wait().
semaphore##
semaphore實現的功能就類似廁所有5個坑,假如有10個人要上廁所,那么同時只能有多少個人去上廁所呢?同時只能有5個人能夠占用,當5個人中 的任何一個人讓開后,其中等待的另外5個人中又有一個人可以占用了。
Semaphore semaphore = new Semaphore(5);
//critical section
semaphore.acquire();
...
semaphore.release();
除了acquire和release,Semaphor還提供了其他接口:
- availablePermits()
- acquireUninterruptibly()
- drainPermits()
- hasQueuedThreads()
- getQueuedThreads()
- tryAcquire()
CountDownLatch##
CyclicBarrier##
CyclicBarrier要做的事情是讓一組線程到達一個屏障時被阻塞,直到最后一個線程到達屏障時,屏障門才會打開。
public class CyclicBarrierTest {
static CyclicBarrier c = new CyclicBarrier(2);
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
try {
c.await();
} catch (Exception e) {
}
System.out.println(1);
}
}).start();
try {
c.await();
} catch (Exception e) {
}
System.out.println(2);
}
}