三线程循环打印ABC
【多线程|Java三线程按序打印10次ABC (Lock实现与synchronized,wait,notify实现)】方法一:使用Lock
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test {static private int cnt = 0;
static Lock lk = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
Thread A = new Thread(new Runnable() {
@Override
public void run() {
while(cnt <= 30) {
lk.lock();
if (cnt % 3 == 0) {
System.out.print("A ");
cnt++;
}
lk.unlock();
}
}
});
Thread B = new Thread(new Runnable() {
@Override
public void run() {
while(cnt <= 30) {
lk.lock();
if (cnt % 3 == 1) {
System.out.print("B ");
cnt++;
}
lk.unlock();
}
}
});
Thread C = new Thread(new Runnable() {
@Override
public void run() {
while(cnt <= 30) {
lk.lock();
if (cnt % 3 == 2) {
System.out.print("C\n");
cnt++;
}
lk.unlock();
}
}
});
A.start();
B.start();
C.start();
}
}
方法二:synchronized,wait,noify实现
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test {public static void main(String[] args) throws InterruptedException {
Object A = new Object();
Object B = new Object();
Object C = new Object();
Thread At = new Thread(new Print(A, B), "A");
Thread Bt = new Thread(new Print(B, C), "B");
Thread Ct = new Thread(new Print(C, A), "C");
At.sleep(100);
At.start();
Bt.sleep(100);
Bt.start();
Ct.sleep(100);
Ct.start();
}
}class Print implements Runnable {Object nxt, cur;
public Print(Object cur, Object nxt) {
this.cur = cur;
this.nxt = nxt;
}
@Override
public void run() {
for(int i = 0;
i < 10;
i++) {
synchronized (cur) {
synchronized (nxt) {
System.out.print(Thread.currentThread().getName());
nxt.notify();
}
try {
cur.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
推荐阅读
- 代码狂魔|实战证明java中的两把锁ReentrantLock与synchronized的系统调用
- 进程通信方式
- 流程控制语句 for循环打印菱形
- 实习第一天(mybites的学习笔记(纯手打))
- 解决方案|大文件拆分方案的java实践
- 多线程编程(1)(共享内存与锁)
- ArrayCopy
- Java|多线程编程(二)——面试题,每个线程只打印一种字符,多个线程协同顺序打印n次字符串(求大神的其他实现方案)
- 支付宝单笔转账实现