先從線程的建立提及.線程的建立一共有兩種形式:
--------------------------------------------------------------------------------
一種是繼承自Thread類.Thread 類是一個具體的類,即不是抽象類,該類封裝了線程的行爲。要建立一個線程,程序員必須建立一個從 Thread 類導出的新類。程序員經過覆蓋 Thread 的 run() 函數來完成有用的工做。用戶並不直接調用此函數;而是經過調用 Thread 的 start() 函數,該函數再調用 run()。
例如:
public class Test extends Thread{
public Test(){
}
public static void main(String args[]){
Test t1 = new Test();
Test t2 = new Test();
t1.start();
t2.start();
}
public void run(){
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"**|----|**"+i);
} }
}
結果:t1和t2兩個線程就交叉執行的,即t1執行一下子,t2執行一下子。
--------------------------------------------------------------------------------
另外一種是實現Runnable接口,此接口只有一個函數,run(),此函數必須由實現了此接口的類實現。
例如:
public class Test implements Runnable{
Thread thread1;
Thread thread2;
public Test(){
thread1 = new Thread(this,"1");
thread2 = new Thread(this,"2");
}
public static void main(String args[]){
Test t = new Test();
t.startThreads();
}
public void run(){
//do thread's things
}
public void startThreads(){
thread1.start();
thread2.start();
}
}
兩種建立方式看起來差異不大,可是弄不清楚的話,也許會將你的程序弄得一團糟。二者區別有如下幾點:
1.當你想繼承某一其它類時,你只能用後一種方式.
2.第一種由於繼承自Thread,只建立了自身對象,可是在數量上,須要幾個線程,就得建立幾個自身對象;第二種只建立一個自身對象,卻建立幾個Thread對象.而兩種方法重大的區別就在於此,請你考慮:若是你在第一種裏建立數個自身對象而且start()後,你會發現好像synchronized不起做用了,已經加鎖的代碼塊或者方法竟然同時能夠有幾個線程進去,並且一樣一個變量,竟然能夠有好幾個線程同時能夠去更改它。(例以下面的代碼)這是由於,在這個程序中,雖然你起了數個線程,但是你也建立了數個對象,並且,每一個線程對應了每一個對象也就是說,每一個線程更改和佔有的對象都不同,因此就出現了同時有幾個線程進入一個方法的現象,其實,那也不是一個方法,而是不一樣對象的相同的方法。因此,這時候你要加鎖的話,只能將方法或者變量聲明爲靜態,將static加上後,你就會發現,線程又能管住方法了,同時不可能有兩個線程進入一樣一個方法,那是由於,如今不是每一個對象都擁有一個方法了,而是全部的對象共同擁有一個方法,這個方法就是靜態方法。
而你若是用第二種方法使用線程的話,就不會有上述的狀況,由於此時,你只建立了一個自身對象,因此,自身對象的屬性和方法對於線程來講是共有的。
所以,建議最好用後一種方法來使用線程。
public class mainThread extends Thread{
int i=0;
public static void main(String args[]){
mainThread m1 = new mainThread();
mainThread m2 = new mainThread();
mainThread m3 = new mainThread();
mainThread m4 = new mainThread();
mainThread m5 = new mainThread();
mainThread m6 = new mainThread();
m1.start();
m2.start();
m3.start();
m4.start();
m5.start();
m6.start();
}
public synchronized void t1(){
i=++i;
try{
Thread.sleep(500);
}
catch(Exception e){}
//每一個線程都進入各自的t1()方法,分別打印各自的i
System.out.println(Thread.currentThread().getName()+" "+i);
}
public void run(){
synchronized(this){
while (true) {
t1();
}
}
}
}java
--------------------------------------------------------------------------------
下面咱們來說synchronized的4種用法吧:
1.方法聲明時使用,放在範圍操做符(public等)以後,返回類型聲明(void等)以前.即一次只能有一個線程進入該方法,其餘線程要想在此時調用該方法,只能排隊等候,當前線程(就是在synchronized方法內部的線程)執行完該方法後,別的線程才能進入.
例如:
public synchronized void synMethod() {
//方法體
}
2.對某一代碼塊使用,synchronized後跟括號,括號裏是變量,這樣,一次只有一個線程進入該代碼塊.例如:
public int synMethod(int a1){
synchronized(a1) {
//一次只能有一個線程進入
}
}
3.synchronized後面括號裏是一對象,此時,線程得到的是對象鎖.例如:
public class MyThread implements Runnable {
public static void main(String args[]) {
MyThread mt = new MyThread();
Thread t1 = new Thread(mt, "t1");
Thread t2 = new Thread(mt, "t2");
Thread t3 = new Thread(mt, "t3");
Thread t4 = new Thread(mt, "t4");
Thread t5 = new Thread(mt, "t5");
Thread t6 = new Thread(mt, "t6");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}
public void run() {
synchronized (this) {
System.out.println(Thread.currentThread().getName());
}
}
}程序員
對於3,若是線程進入,則獲得對象鎖,那麼別的線程在該類全部對象上的任何操做都不能進行.在對象級使用鎖一般是一種比較粗糙的方法。爲何要將整個對象都上鎖,而不容許其餘線程短暫地使用對象中其餘同步方法來訪問共享資源?若是一個對象擁有多個資源,就不須要只爲了讓一個線程使用其中一部分資源,就將全部線程都鎖在外面。因爲每一個對象都有鎖,能夠以下所示使用虛擬對象來上鎖:
class FineGrainLock {
MyMemberClass x, y;
Object xlock = new Object(), ylock = new Object();
public void foo() {
synchronized(xlock) {
//access x here
}
//do something here - but don't use shared resources
synchronized(ylock) {
//access y here
}
}
public void bar() {
synchronized(this) {
//access both x and y here
}
//do something here - but don't use shared resources
}
}
4.synchronized後面括號裏是類.例如:
class ArrayWithLockOrder{
private static long num_locks = 0;
private long lock_order;
private int[] arr;
public ArrayWithLockOrder(int[] a)
{
arr = a;
synchronized(ArrayWithLockOrder.class) {//-----------------------------------------這裏
num_locks++; // 鎖數加 1。
lock_order = num_locks; // 爲此對象實例設置惟一的 lock_order。
}
}
public long lockOrder()
{
return lock_order;
}
public int[] array()
{
return arr;
}
}
class SomeClass implements Runnable
{
public int sumArrays(ArrayWithLockOrder a1,
ArrayWithLockOrder a2)
{
int value = 0;
ArrayWithLockOrder first = a1; // 保留數組引用的一個
ArrayWithLockOrder last = a2; // 本地副本。
int size = a1.array().length;
if (size == a2.array().length)
{
if (a1.lockOrder() > a2.lockOrder()) // 肯定並設置對象的鎖定
{ // 順序。
first = a2;
last = a1;
}
synchronized(first) { // 按正確的順序鎖定對象。
synchronized(last) {
int[] arr1 = a1.array();
int[] arr2 = a2.array();
for (int i=0; i<size; i++)
value += arr1[i] + arr2[i];
}
}
}
return value;
}
public void run() {
//...
}
}
對於4,若是線程進入,則線程在該類中全部操做不能進行,包括靜態變量和靜態方法,實際上,對於含有靜態方法和靜態變量的代碼塊的同步,咱們一般用4來加鎖.
以上4種之間的關係:
鎖是和對象相關聯的,每一個對象有一把鎖,爲了執行synchronized語句,線程必須可以得到synchronized語句中表達式指定的對象的鎖,一個對象只有一把鎖,被一個線程得到以後它就再也不擁有這把鎖,線程在執行完synchronized語句後,將得到鎖交還給對象。
在方法前面加上synchronized修飾符便可以將一個方法聲明爲同步化方法。同步化方法在執行以前得到一個鎖。若是這是一個類方法,那麼得到的鎖是和聲明方法的類相關的Class類對象的鎖。若是這是一個實例方法,那麼此鎖是this對象的鎖。
數組
--------------------------------------------------------------------------------jvm
下面談一談一些經常使用的方法:
wait(),wait(long),notify(),notifyAll()等方法是當前類的實例方法,
wait()是使持有對象鎖的線程釋放鎖;
wait(long)是使持有對象鎖的線程釋放鎖時間爲long(毫秒)後,再次得到鎖,wait()和wait(0)等價;
notify()是喚醒一個正在等待該對象鎖的線程,若是等待的線程不止一個,那麼被喚醒的線程由jvm肯定;
notifyAll是喚醒全部正在等待該對象鎖的線程.
在這裏我也重申一下,咱們應該優先使用notifyAll()方法,由於喚醒全部線程比喚醒一個線程更容易讓jvm找到最適合被喚醒的線程.
對於上述方法,只有在當前線程中才能使用,不然報運行時錯誤java.lang.IllegalMonitorStateException: current thread not owner.
--------------------------------------------------------------------------------ide
下面,我談一下synchronized和wait()、notify()等的關係:
1.有synchronized的地方不必定有wait,notify
2.有wait,notify的地方必有synchronized.這是由於wait和notify不是屬於線程類,而是每個對象都具備的方法,並且,這兩個方法都和對象鎖有關,有鎖的地方,必有synchronized。
另外,請注意一點:若是要把notify和wait方法放在一塊兒用的話,必須先調用notify後調用wait,由於若是調用完wait,該線程就已經不是current thread了。以下例:函數
import java.lang.Runnable;
import java.lang.Thread;
public class DemoThread
implements Runnable {
public DemoThread() {
TestThread testthread1 = new TestThread(this, "1");
TestThread testthread2 = new TestThread(this, "2");
testthread2.start();
testthread1.start();
}
public static void main(String[] args) {
DemoThread demoThread1 = new DemoThread();
}
public void run() {
TestThread t = (TestThread) Thread.currentThread();
try {
if (!t.getName().equalsIgnoreCase("1")) {
synchronized (this) {
wait();
}
}
while (true) {
System.out.println("@time in thread" + t.getName() + "=" +
t.increaseTime());
if (t.getTime() % 10 == 0) {
synchronized (this) {
System.out.println("****************************************");
notify();
if (t.getTime() == 100)
break;
wait();
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
class TestThread
extends Thread {
private int time = 0;
public TestThread(Runnable r, String name) {
super(r, name);
}
public int getTime() {
return time;
}
public int increaseTime() {
return++time;
}
}
下面咱們用生產者/消費者這個例子來講明他們之間的關係:
public class test {
public static void main(String args[]) {
Semaphore s = new Semaphore(1);
Thread t1 = new Thread(s, "producer1");
Thread t2 = new Thread(s, "producer2");
Thread t3 = new Thread(s, "producer3");
Thread t4 = new Thread(s, "consumer1");
Thread t5 = new Thread(s, "consumer2");
Thread t6 = new Thread(s, "consumer3");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}
}
class Semaphore
implements Runnable {
private int count;
public Semaphore(int n) {
this.count = n;
}
public synchronized void acquire() {
while (count == 0) {
try {
wait();
}
catch (InterruptedException e) {
//keep trying
}
}
count--;
}
public synchronized void release() {
while (count == 10) {
try {
wait();
}
catch (InterruptedException e) {
//keep trying
}
}
count++;
notifyAll(); //alert a thread that's blocking on this semaphore
}
public void run() {
while (true) {
if (Thread.currentThread().getName().substring(0,8).equalsIgnoreCase("consumer")) {
acquire();
}
else if (Thread.currentThread().getName().substring(0,8).equalsIgnoreCase("producer")) {
release();
}
System.out.println(Thread.currentThread().getName() + " " + count);
}
}
}
生產者生產,消費者消費,通常沒有衝突,但當庫存爲0時,消費者要消費是不行的,但當庫存爲上限(這裏是10)時,生產者也不能生產.請好好研讀上面的程序,你必定會比之前進步不少.
上面的代碼說明了synchronized和wait,notify沒有絕對的關係,在synchronized聲明的方法、代碼塊中,你徹底能夠不用wait,notify等方法,可是,若是當線程對某一資源存在某種爭用的狀況下,你必須適時得將線程放入等待或者喚醒.ui