1、3个线程交替输出1-100
/**
* 需求:
* 3个线程交替输出1-100
*/
public class TestPrint1_100 {
private Integer state = 1; // 状态值1-t1执行, 2-t2执行, 3-t3执行
private Integer count = 1; // 循环次数初始值
public void print1_100(TestPrint1_100 print1_100) {
Thread t1 = new Thread(() -> {
excute1_100(print1_100, 1, 2);
});
Thread t2 = new Thread(() -> {
excute1_100(print1_100, 2, 3);
});
Thread t3 = new Thread(() -> {
excute1_100(print1_100, 3, 1);
});
t2.start();
t3.start();
try {
// 确保执行顺序
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.start();
}
/**
*
* @param print1_100 共享对象,用于对象锁
* @param curState 当前现在状态
* @param nextState 下一个线程状态
*/
public void excute1_100(TestPrint1_100 print1_100, int curState, int nextState) {
while (count <= 100) { // 循环条件
synchronized (print1_100) { // 同一个对象锁
if (state == curState) { // 状态值为当前线程的状态值才执行
System.out.println(Thread.currentThread().getName() + " - " + count);
state = nextState; // 下个线程的状态值赋值给状态值
count++; // 循环条件自增
print1_100.notifyAll(); // 唤醒所有的线程准备抢锁
}else {
try {
print1_100.wait(); // 线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
TestPrint1_100 print1_100 = new TestPrint1_100();
print1_100.print1_100(print1_100);
}
}
2、3个线程交替输出ABC
/**
* 需求:
* 3个线程交替输出ABC 3次
*/
public class TestPrintA_C {
private Integer state = 1; // 状态值1-t1执行, 2-t2执行, 3-t3执行
private Integer count = 1; // 循环次数初始值
public void printA_C(TestPrintA_C printA_C) {
Thread t1 = new Thread(() -> {
excuteA_C(printA_C, "A", 1, 2);
});
Thread t2 = new Thread(() -> {
excuteA_C(printA_C, "B", 2, 3);
});
Thread t3 = new Thread(() -> {
excuteA_C(printA_C, "C", 3, 1);
});
t2.start();
t3.start();
try {
// 确保执行顺序
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.start();
}
/**
*
* @param printA_C 共享对象,用于对象锁
* @param data 需要输出的值
* @param curState 当前现在状态
* @param nextState 下一个线程状态
*/
public void excuteA_C(TestPrintA_C printA_C, String data, int curState, int nextState) {
while (count <= 9) { // 循环条件 3 * N,N代表交替输出的次数
synchronized (printA_C) { // 同一个对象锁
if (state == curState) { // 状态值为当前线程的状态值才执行
System.out.println(Thread.currentThread().getName() + " - " + data);
state = nextState; // 下个线程的状态值赋值给状态值
count++; // 循环条件自增
printA_C.notifyAll(); // 唤醒所有的线程准备抢锁
}else {
try {
printA_C.wait(); // 线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
TestPrintA_C printA_C = new TestPrintA_C();
printA_C.printA_C(printA_C);
}
}
标签:print1,输出,ABC,Thread,param,printA,交替,线程,100
From: https://www.cnblogs.com/xiaonuanxin/p/17565675.html