Java多线程实现同时输出
一道经典的面试题目:两个线程,分别打印AB,其中线程A打印A,线程B打印B,各打印10次,使之出现ABABABABA..的效果
packagecom.shangshe.path;
publicclassThreadAB{
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
finalPrintbusiness=newPrint();
newThread(newRunnable(){
publicvoidrun(){
for(inti=0;i<10;i++){
business.print_A();
}
}
}).start();
newThread(newRunnable(){
publicvoidrun(){
for(inti=0;i<10;i++){
business.print_B();
}
}
}).start();
}
}
classPrint{
privatebooleanflag=true;
publicsynchronizedvoidprint_A(){
while(!flag){
try{
this.wait();
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
System.out.print("A");
flag=false;
this.notify();
}
publicsynchronizedvoidprint_B(){
while(flag){
try{
this.wait();
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
System.out.print("B");
flag=true;
this.notify();
}
}
由上面的例子我们可以设计出3个线程乃至于n个线程的程序,下面给出的例子是3个线程,分别打印A,B,C10次,使之出现ABCABC..的效果
publicclassThreadABC{
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
finalPrintbusiness=newPrint();
newThread(newRunnable(){
publicvoidrun(){
for(inti=0;i<100;i++){
business.print_A();
}
}
}).start();
newThread(newRunnable(){
publicvoidrun(){
for(inti=0;i<100;i++){
business.print_B();
}
}
}).start();
newThread(newRunnable(){
publicvoidrun(){
for(inti=0;i<100;i++){
business.print_C();
}
}
}).start();
}
}
classPrint{
privatebooleanshould_a=true;
privatebooleanshould_b=false;
privatebooleanshould_c=false;
publicsynchronizedvoidprint_A(){
while(should_b||should_c){
try{
this.wait();
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
System.out.print("A");
should_a=false;
should_b=true;
should_c=false;
this.notifyAll();
}
publicsynchronizedvoidprint_B(){
while(should_a||should_c){
try{
this.wait();
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
System.out.print("B");
should_a=false;
should_b=false;
should_c=true;
this.notifyAll();
}
publicsynchronizedvoidprint_C(){
while(should_a||should_b){
try{
this.wait();
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
System.out.print("C");
should_a=true;
should_b=false;
should_c=false;
this.notifyAll();
}
}
再一次证明了软件工程的重要性了;在多线程程序中,应该说在程序中,我们应该把那些业务逻辑代码放到同一个类中,使之高内聚,低耦合
热门推荐
10 喜得新房文案祝福语简短
11 中秋祝福语送朋友简短
12 少先队代表送祝福语简短
13 新年过后奋斗祝福语简短
14 开学新人祝福语简短英语
15 周日徒步祝福语大全简短
16 离校发给老师祝福语简短
17 职场离职文案祝福语简短
18 除夕的拜年祝福语简短