1.题目描述
启动三个线程,三个线程名称分别是A,B,C;每个线程将自己的名称在屏幕上打印5遍,打印顺序是ABCABCABCABCABC
2.解题思路
2.1写打印A、B、C的方法
//设置标记位,判断应该打印哪个线程名
private int flag = 1;
//记录打印次数
private int count = 1;
//打印线程名称A方法
// 顺序打印,用锁
public synchronized void PrintA(){
// 如果falg不为1,等待
while (flag != 1){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 打印当前线程名
System.out.print(Thread.currentThread().getName());
// 使其可以进入打印线程B方法
flag = 2;
notifyAll();
// 打印次数+1
count++;
}
//打印线程名称B方法
public synchronized void PrintB(){
while (flag != 2){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName());
flag = 3;
notifyAll();
count++;
}
//打印线程名称C方法
public synchronized void PrintC(){
while (flag != 3){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName());
flag = 1;
notifyAll();
count++;
}
2.2写MyThread类调用三个打印方法
class MyThread implements Runnable{
public PrintTest1 printTest1;
public MyThread(PrintTest1 printTest1){
this.printTest1 = printTest1;
}
@Override
public void run() {
// 因为最后一次打印A时count=13
while(printTest1.getCount()<14){
if(Thread.currentThread().getName().equals("A")){
printTest1.PrintA();
}
if(Thread.currentThread().getName().equals("B")){
printTest1.PrintB();
}
if(Thread.currentThread().getName().equals("C")){
printTest1.PrintC();
}
}
}
}
3.整体代码如下
/**
* 2.启动三个线程,三个线程名称分别是A,B,C;
* 每个线程将自己的名称在屏幕上打印5遍,打印顺序是ABCABCABCABCABC
*/
class PrintTest1{
private int flag=1;
private int count=1;
public int getCount(){
return count;
}
public synchronized void PrintA(){
while (flag != 1){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName());
flag = 2;
notifyAll();
count++;
}
public synchronized void PrintB(){
while (flag != 2){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName());
flag = 3;
notifyAll();
count++;
}
public synchronized void PrintC(){
while (flag != 3){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName());
flag = 1;
notifyAll();
count++;
}
}
class MyThread implements Runnable{
public PrintTest1 printTest1;
public MyThread(PrintTest1 printTest1){
this.printTest1 = printTest1;
}
@Override
public void run() {
while(printTest1.getCount()<14){
if(Thread.currentThread().getName().equals("A")){
printTest1.PrintA();
}
if(Thread.currentThread().getName().equals("B")){
printTest1.PrintB();
}
if(Thread.currentThread().getName().equals("C")){
printTest1.PrintC();
}
}
}
}
public class Test2 {
public static void main(String[] args) {
PrintTest1 printTest1 = new PrintTest1();
MyThread myThread = new MyThread(printTest1);
new Thread(myThread,"A").start();
new Thread(myThread,"B").start();
new Thread(myThread,"C").start();
}
}
4.运行结果