2022年1月17日更新一版
public class Test2 implements Runnable {
int i = 0;
private synchronized void printChar() {
if(i==0) {
System.out.println("A");
i++;
} else if(i==1) {
System.out.println("B");
i++;
} else {
System.out.println("C");
i = 0;
}
}
public static void main(String[] args) {
int count = 100;
Test2 test2 = new Test2();
for (int i = 0; i < count; i++) {
Thread threadA = new Thread(test2, "tA");
Thread threadB = new Thread(test2, "tB");
Thread threadC = new Thread(test2, "tC");
threadA.start();
threadB.start();
threadC.start();
}
}
@Override
public void run() {
printChar();
}
}
以下为2019-07-28 21:27:59写的,太业余!!
之前看了个题目,利用多线程顺序打印10次ABC,方法有多种,以下也是一种思路。
不过,这样写,循环多少次,就需要创建多少个线程,性能不是很好
package com.thread.chapter1;
public class PrintABC {
Object lock = new Object();
boolean isA = true, // 第一次要先打印A,所以默认值为true
isB = false, isC = false;
public static void main(String[] args) throws InterruptedException {
PrintABC printABC = new PrintABC();
for (int i = 0; i < 10; i++) {
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
try {
printABC.printA(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
try {
printABC.printB(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread threadC = new Thread(new Runnable() {
@Override
public void run() {
try {
printABC.printC(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
threadA.start();
Thread.sleep(100); // 如果不加sleep 100,容易打印不够10次,
// 竞争太厉害,容易造成死锁等待(即isA/isB/isC都为false)
threadB.start();
Thread.sleep(100);
threadC.start();
Thread.sleep(100);
}
System.out.println("main");
}
private void printA(String threadName) throws InterruptedException {
synchronized (lock) {
while (!isA) {
lock.wait(); //wait/notify要配合synchronized使用
}
System.out.println("A:: "+threadName);
isA = false;
isB = true;
lock.notify();
}
}
private void printB(String threadName) throws InterruptedException {
synchronized (lock) {
while (!isB) {
lock.wait();
}
System.out.println("B:: "+threadName);
isB = false;
isC = true;
lock.notify();
}
}
private void printC(String threadName) throws InterruptedException {
synchronized (lock) {
while (!isC) {
lock.wait();
}
System.out.println("C:: "+threadName);
isC = false;
isA = true;
}
}
}