1.使用synchronized代碼塊及其原理
2.使用synchronized方法
3.分析靜態方法所使用的同步監視對象是什麼?
4.Wait與notify實現線程間的通信
(1)用面試寶典中的子線程循環10次和主線程循環5次,兩者交替運行50的例子進行講解。
(2)爲了觀察程序的運行結果,可以在eclipse中設置運行對話框,讓結果重定向到一個文本文件,然後用UE去查看該文本文件中的特殊的行號處是否正好對應了線程的切換點。
經驗:要用到共同數據(包括同步鎖)的若干個方法應該歸在同一個類身上,這種設計正好體現了高類聚和程序的健壯性。//重點理解這句話實例
1:使用同步方法,或者同步代碼塊 實現方法的互斥
public class ThreadDemo_01{
public static void main(String[] args) {
final Outputer output=new Outputer();
new Thread(new Runnable() {
@Override
public void run() {
while(true){
output.output("xiaoming");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true){
output.output2("xiaohong");
}
}
}).start();
}
static class Outputer{
public void output(String name){
synchronized (this) {
int length=name.length();
for (int i = 0; i < length; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
/*
靜態方法的默認鎖是:類的字節碼
普通方法的默認鎖是:this
*/
public synchronized static void output2(String name){
int length=name.length();
for (int i = 0; i < length; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
實例2:使用同步方法,或者同步代碼塊 實現方法的互斥
使用 信號量,wait與notify方法實現線程間的通信,同步
public class TraditionalThreadCommunication { public static void main(String[] args) { final Business business = new Business(); new Thread( new Runnable() { @Override public void run() { for(int i=1;i<=50;i++){ business.sub(i); } } } ).start(); for(int i=1;i<=50;i++){ business.main(i); } } } class Business { private boolean bShouldSub = true; public synchronized void sub(int i){ while(!bShouldSub){ //此處使用while比使用if好,防止線程的虛假喚醒(機率小,但是也要考慮),要使用while更安全 try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int j=1;j<=10;j++){ System.out.println("sub thread sequence of " + j + ",loop of " + i); } bShouldSub = false; this.notify(); } public synchronized void main(int i){ while(bShouldSub){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int j=1;j<=100;j++){ System.out.println("main thread sequence of " + j + ",loop of " + i); } bShouldSub = true; this.notify(); } }