java多執行緒同步案列---按照固定格式輸出數字和字母
1個執行緒從1~26輸出
1個執行緒從a~z輸出
1個執行緒從A~Z輸出
輸出格式為:
1 a A
2 b B
3 c C
4 d D
...
26 z Z*/
//首先建立一個公用類PrintAll
public class PrintAll {
int all = 1;//定義一個屬性all
//建立列印數字的方法
public synchronized void num(){
for (int i = 1; i <= 26; i++) {
while(all != 1){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(i);
all = 2;
notifyAll();
}
}
public synchronized void lower(){
for(char a = 'a';a <= 'z';a++){
while(all != 2){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(" " + a);
all = 3;
notifyAll();
}
}
public synchronized void upper(){
for (char a = 'A'; a <= 'Z' ; a++) {
while(all != 3){
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(" " + a);
all = 1;
notifyAll();
}
}
}
//建立一個列印數字的執行緒類
public class Num extends Thread{
PrintAll p = new PrintAll();//根據PrintAll物件實現執行緒同步
//建立構造方法,將PrintAll物件傳入
public Num(PrintAll p) {
this.p = p;
}
public void run(){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
//呼叫公用物件中的列印數字方法
p.num();
}
}
//建立一個列印小寫字母的執行緒類
public class Lower extends Thread {
PrintAll p = new PrintAll();//根據PrintAll物件實現執行緒同步
//建立構造方法,將PrintAll物件傳入
public Lower(PrintAll p) {
this.p = p;
}
public void run(){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
//呼叫公用物件中的列印小寫字母的方法
p.lower();
}
}
//建立一個列印大寫字母的執行緒類
public class Upper extends Thread{
PrintAll p = new PrintAll();//根據PrintAll物件實現執行緒同步
//建立構造方法,將PrintAll物件傳入
public Upper(PrintAll p) {
this.p = p;
}
public void run(){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
//呼叫公用物件中的列印大寫字母的方法
p.upper();
}
}
//建立測試類
public class Test {
public static void main(String[] args) {
//建立一個公用的物件,保證執行緒的同步(注:這裡只能new一個倉庫物件)
PrintAll p = new PrintAll();
//分別建立三個執行緒類,將p物件傳入
Num n = new Num(p);
Lower l = new Lower(p);
Upper u = new Upper(p);
//啟動執行緒
n.start();
l.start();
u.start();
}
}