Thread练习

题目:现有三个线程,分别用于打印10次A,B,C,现在要求通过代码控制,实现线程按照先后顺序打印出ABCABCABCABCABCABCABCABCABCABC


我写的代码如下:

package com.example.testabc;

public class TChar {
	private char c;
	
	public TChar(char c){
		this.c = c;
	}

	public char getC() {
		return c;
	}

	public void setC(char c) {
		this.c = c;
	}
	
}

package com.example.testabc;

public class PrintA implements Runnable{
	private TChar currentChar;
	
	public PrintA(TChar tchar){
		this.currentChar = tchar;
	}
	
	private void printChar(){
		synchronized(currentChar){
			while(currentChar.getC() != 'C'){
				try {
					currentChar.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.printf("%c", 'A');
			currentChar.setC('A');
			currentChar.notifyAll();
		}
		
	}

	@Override
	public void run() {
		for(int i=0; i<10; i++){
			printChar();
		}
	}
	
}

package com.example.testabc;

public class PrintB implements Runnable{
	private TChar currentChar;
	
	public PrintB(TChar tchar){
		this.currentChar = tchar;
	}
	
	private void printChar(){
		synchronized(currentChar){
			while(currentChar.getC() != 'A'){
				try {
					currentChar.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.printf("%c", 'B');
			currentChar.setC('B');
			currentChar.notifyAll();
		}
	}
	
	@Override
	public void run() {
		for(int i=0; i<10; i++){
			printChar();
		}
	}
}

package com.example.testabc;

public class PrintC implements Runnable{
	private TChar currentChar;
	
	public PrintC(TChar tchar){
		this.currentChar = tchar;
	}
	
	private void printChar(){
		synchronized(currentChar){
			while(currentChar.getC() != 'B'){
				try {
					currentChar.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.printf("%c", 'C');
			currentChar.setC('C');
			currentChar.notifyAll();
		}
	}
	
	@Override
	public void run() {
		for(int i=0; i<10; i++){
			printChar();
		}
	}
}

package com.example.testabc;

public class TestABC{
		
	public static void main(String[] args){
		TChar cchar = new TChar('C');
		PrintA pa = new PrintA(cchar);
		PrintB pb = new PrintB(cchar);
		PrintC pc = new PrintC(cchar);
		
		Thread threadA = new Thread(pa);
		Thread threadB = new Thread(pb);
		Thread threadC = new Thread(pc);
		
		threadA.start();
		threadB.start();
		threadC.start();
		
	}
}

写得比较繁琐,希望大家可以给出自己的答案,一起分享。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值