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.運行結果