接本系列上篇。
3)原子操作
原子操作不需要進行同步控制。
何謂原子操作?原子操作就是對除了long以及double數據類型外的基本類型,進行簡單的變量賦值或是返回值操作。
自增自減操作也不是原子操作。
4)臨界區
爲防止多個線程同時訪問方法內部的部分代碼,也可以用synchronized建立。
Synchronized(syncObject){
//...
}
這種叫同步控制塊。在進入這個塊前,必須先獲得鎖。若此時鎖已經被其他線程獲得,則需要等待。
5)線程間協作
Wait、notify、notifyall均屬於object對象的方法,都是隻能用在同步塊才能使用的函數,並且是要在調用這些函數前獲得這些鎖,通常是如下形式。
Synchronized(syncObject){
syncObject.notify();
}
Sleep則屬於thread對象的方法,可以在非同步塊使用。
小貼士
一個關於Java Thread wait(),notify()的實用例——生產者消費者實例
/////
// ProducerConsumer.java
//
// @author 葉雨
//
// 這是個很重要的Thread例子。需要注意的是:
// wait() 必須在synchronized 函數或者代碼塊裏面
// wait()會讓已經獲得synchronized 函數或者代碼塊控制權的Thread暫時休息,並且喪失控制權
// 這個時候,由於該線程喪失控制權並且進入等待,其他線程就能取得控制權,並且在適當情況下調用notifyAll()來喚醒wait()的線程。
// 需要注意的是,被喚醒的線程由於已經喪失了控制權,所以需要等待喚醒它的線程結束操作,從而才能重新獲得控制權。
//
// 所以wait()的確是馬上讓當前線程喪失控制權,其他的線程可以乘虛而入。
//
// 所以wait()的使用,必須存在2個以上線程,而且必須在不同的條件下喚醒wait()中的線程。
//
//
// 以下的例子:
// ProductStack 是一個生產者跟消費者共享的同步機制,這個機制決定了什麼情況生產者要wait(),什麼情況消費者要wait()
// 可以把ProductStack看作一個產品倉庫。當產品倉庫滿的時候,生產者線程需要wait(),從而放棄對產品倉庫的控制。
// 這個時候消費者線程就可以進來了而取得倉庫的控制權。一旦消費者消費了產品,那麼倉庫就不滿了。
// 這個時候消費者線程就要notifyAll()生產者線程,讓等待的生產者線程喚醒。
// 但是生產者被喚醒後不能馬上進行生產,因爲它在wait()的時候已經喪失了對倉庫的控制權,所以就需要等待消費者線程結束操作,
// 才能重新取得倉庫的控制權,再進行生產。
//
// 所以特別注意的是,notifyAll()並不是讓當前線程馬上讓出控制權,而只是讓其他wait()當中的線程喚醒而已,
// 所以對不起,儘管我喚醒你,可你必須還是要等我用完倉庫才能進來。這點必須清楚。
//
// 相反,倉庫如果空的時候,消費者線程就會wait(),然後等待生產者線程來生產產品,生產者進程乘虛而入後,讓生產者線程生產產品
// 並且喚醒消費者線程。這個情況跟上面就類似了。
//
///
package cn.com.dang;
public class ProducerConsumer {
public static void main(String[] args) {
ProductStack ps = new ProductStack();
Producer p = new Producer(ps, "生產者1");
Consumer c = new Consumer(ps, "消費者1");
new Thread(p).start();
new Thread(c).start();
}
}
class Product {
int id;
private String producedBy = "N/A";
private String consumedBy = "N/A";
// 構造函數,指明產品ID以及生產者名字。
Product(int id, String producedBy) {
this.id = id;
this.producedBy = producedBy;
}
// 消費,需要指明消費者名字
public void consume(String consumedBy) {
this.consumedBy = consumedBy;
}
public String toString() {
return "Product : " + id + ", produced by " + producedBy
+ ", consumed by " + consumedBy;
}
public String getProducedBy() {
return producedBy;
}
public void setProducedBy(String producedBy) {
this.producedBy = producedBy;
}
public String getConsumedBy() {
return consumedBy;
}
public void setConsumedBy(String consumedBy) {
this.consumedBy = consumedBy;
}
}
// 這個class就是倉庫,是生產者跟消費者共同爭奪控制權的同步資源
class ProductStack {
int index = 0;
Product[] arrProduct = new Product[6];
// push使用來讓生產者放置產品的
public synchronized void push(Product product) {
// 如果倉庫滿了
while (index == arrProduct.length) // 這裏本來可以用if(),但是如果catch
// exception會出問題,讓滿的index越界
{
try {
// here, "this" means the thread that is using "push"
// so in this case it's a producer thread instance.
// the BIG difference between sleep() and wait() is, once
// wait(),
// the thread won't have the lock anymore
// so when a producer wait() here, it will lost the lock of
// "push()"
// While sleep() is still keeping this lock
// Important: wait() and notify() should be in "synchronized"
// block
System.out.println(product.getProducedBy() + " is waiting.");
// 等待,並且從這裏退出push()
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(product.getProducedBy() + " sent a notifyAll().");
// 因爲我們不確定有沒有線程在wait(),所以我們既然生產了產品,就喚醒有可能等待的消費者,讓他們醒來,準備消費
notifyAll();
// 注意,notifyAll()以後,並沒有退出,而是繼續執行直到完成。
arrProduct[index] = product;
index++;
System.out.println(product.getProducedBy() + " 生產了: " + product);
}
// pop用來讓消費者取出產品的
public synchronized Product pop(String consumerName) {
// 如果倉庫空了
while (index == 0) {
try {
// here will be the consumer thread instance will be waiting ,
// because empty
System.out.println(consumerName + " is waiting.");
// 等待,並且從這裏退出pop()
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(consumerName + " sent a notifyAll().");
// 因爲我們不確定有沒有線程在wait(),所以我們既然消費了產品,就喚醒有可能等待的生產者,讓他們醒來,準備生產
notifyAll();
// 注意,notifyAll()以後,並沒有退出,而是繼續執行直到完成。
// 取出產品
index--;
Product product = arrProduct[index];
product.consume(consumerName);
System.out.println(product.getConsumedBy() + " 消費了: " + product);
return product;
}
}
class Producer implements Runnable {
String name;
ProductStack ps = null;
Producer(ProductStack ps, String name) {
this.ps = ps;
this.name = name;
}
public void run() {
for (int i = 0; i < 20; i++) {
Product product = new Product(i, name);
ps.push(product);
try {
Thread.sleep((int) (Math.random() * 200));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
String name;
ProductStack ps = null;
Consumer(ProductStack ps, String name) {
this.ps = ps;
this.name = name;
}
public void run() {
for (int i = 0; i < 20; i++) {
Product product = ps.pop(name);
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}