java同时输出_Java多线程实现同时输出

一道经典的面试题目:两个线程,分别打印AB,其中线程A打印A,线程B打印B,各打印10次,使之出现ABABABABA.. 的效果

package com.shangshe.path;

public class ThreadAB {

/**

* @param args

*/

public static void main(String[] args) {

final Print business = new Print();

new Thread(new Runnable() {

public void run() {

for(int i=0;i<10;i++) {

business.print_A();

}

}

}).start();

new Thread(new Runnable() {

public void run() {

for(int i=0;i<10;i++) {

business.print_B();

}

}

}).start();

}

}

class Print {

private boolean flag = true;

public synchronized void print_A () {

while(!flag) {

try {

this.wait();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

System.out.print("A");

flag = false;

this.notify();

}

public synchronized void print_B () {

while(flag) {

try {

this.wait();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

System.out.print("B");

flag = true;

this.notify();

}

}

由上面的例子我们可以设计出3个线程乃至于n个线程的程序,下面给出的例子是3个线程,分别打印A,B,C 10次,使之出现ABCABC.. 的效果

public class ThreadABC {

/**

* @param args

*/

public static void main(String[] args) {

final Print business = new Print();

new Thread(new Runnable() {

public void run() {

for(int i=0;i<100;i++) {

business.print_A();

}

}

}).start();

new Thread(new Runnable() {

public void run() {

for(int i=0;i<100;i++) {

business.print_B();

}

}

}).start();

new Thread(new Runnable() {

public void run() {

for(int i=0;i<100;i++) {

business.print_C();

}

}

}).start();

}

}

class Print {

private boolean should_a = true;

private boolean should_b = false;

private boolean should_c = false;

public synchronized void print_A () {

while(should_b || should_c) {

try {

this.wait();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

System.out.print("A");

should_a = false;

should_b = true;

should_c = false;

this.notifyAll();

}

public synchronized void print_B () {

while(should_a || should_c) {

try {

this.wait();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

System.out.print("B");

should_a = false;

should_b = false;

should_c = true;

this.notifyAll();

}

public synchronized void print_C () {

while(should_a || should_b) {

try {

this.wait();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

System.out.print("C");

should_a = true;

should_b = false;

should_c = false;

this.notifyAll();

}

}

再一次证明了软件工程的重要性了;在多线程程序中,应该说在程序中,我们应该把那些业务逻辑代码放到同一个类中,使之高内聚,低耦合

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值