有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABCABC.

网上一个有意思的题目:
有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABCABC.
以下是我的实现方式:
 public class Main {
public static void main(String[] args){
Data data=new Data();
new ThreadA("A",data).start();
new ThreadB("B",data).start();
new ThreadC("C",data).start();
}
}


public class ThreadA extends Thread{
private Data data;
public ThreadA(String name,Data data){
super(name);
this.data=data;
}
public void run(){
try{
for(int i=0;i<10;i++){
data.writeA();
Thread.sleep(1000);
}
}catch(InterruptedException e){

}
}
}


public class ThreadB extends Thread{
private Data data;
public ThreadB(String name,Data data){
super(name);
this.data=data;
}
public void run(){
try{
for(int i=0;i<10;i++){
data.writeB();
Thread.sleep(1000);
}
}catch(InterruptedException e){

}
}
}


public class ThreadC extends Thread{
private Data data;
public ThreadC(String name,Data data){
super(name);
this.data=data;
}

public void run(){
try{
for(int i=0;i<10;i++){
data.writeC();
Thread.sleep(1000);
}
}catch(InterruptedException e){

}
}
}


public class Data {
private DataBlock block=new DataBlock();

public void writeA()throws InterruptedException{
block.lockA();
try{
System.out.print("A");
}finally{
block.unlockA();
}
}

public void writeB()throws InterruptedException{
block.lockB();
try{
System.out.print("B");
}finally{
block.unlockB();
}
}

public void writeC()throws InterruptedException{
block.lockC();
try{
System.out.print("C");
}finally{
block.unlockC();
}
}
}


package com.thread.xunlei;

public class DataBlock {
private int flag=1;

public synchronized void lockA() throws InterruptedException{
while( flag!=1 ){
wait();
}
}

public synchronized void unlockA(){
flag=2;
notifyAll();
}

public synchronized void lockB() throws InterruptedException{
while( flag!=2 ){
wait();
}
}

public synchronized void unlockB(){
flag=3;
notifyAll();
}

public synchronized void lockC() throws InterruptedException{
while( flag!=3 ){
wait();
}
}

public synchronized void unlockC(){
flag=1;
notifyAll();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值