题目:现有三个线程,分别用于打印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();
}
}
写得比较繁琐,希望大家可以给出自己的答案,一起分享。