一、兩個線程交叉打印100以內奇偶數,打印結束後線程正常結束。
實現方式一:直接使用Lock就可以。初始化線程時在線程中設置一個標識,0代表打印偶數,1代表打印奇數。
定義一個全局變量num代表要打印的數字,在線程中判斷當前要打印的數字是不是和本線程一直,即奇數=奇數線程,偶數對應偶數線程,如果一直則打印,num++,同時喚醒另外的線程;否則進行等待。
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test14 {
public static void main(String[] args) throws Exception {
Test14 t = new Test14();
t.run();
}
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();//獲取condition對象
int num = 1;
void run() throws Exception {
new Thread(new PrintThread(0)).start();
new Thread(new PrintThread(1)).start();
}
class PrintThread implements Runnable {
int id;
public PrintThread(int id) {
this.id = id;
}
public void run() {
while (num <= 100) {
lock.lock();//獲取鎖,上鎖
try {
if (num % 2 == id) {
System.out.println("id " + id + " - " + num);
num ++;
condition.signalAll();//喚醒所有等待線程。能夠從等待方法返回的線程必須獲得與Condition相關的鎖。
} else {
condition.await();//造成當前線程在接到信號或被中斷之前一直處於等待狀態。
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();//解鎖
}
}
}
}
}
實現方式二:
二、3個線程交替打印ABC
1.通過ReentrantLock我們可以很方便的進行顯式的鎖操作,即獲取鎖和釋放鎖,對於同一個對象鎖而言,統一時刻只可能有一個線程拿到了這個鎖,此時其他線程通過lock.lock()來獲取對象鎖時都會被阻塞,直到這個線程通過lock.unlock()操作釋放這個鎖後,其他線程才能拿到這個鎖。
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ABC_Lock {
private static Lock lock = new ReentrantLock();// 通過JDK5中的Lock鎖來保證線程的訪問的互斥
private static int state = 0;//通過state的值來確定是否打印
static class ThreadA extends Thread {
@Override
public void run() {
for (int i = 0; i < 10;) {
try {
lock.lock();
while (state % 3 == 0) {// 多線程併發,不能用if,必須用循環測試等待條件,避免虛假喚醒
System.out.print("A");
state++;
i++;
}
} finally {
lock.unlock();// unlock()操作必須放在finally塊中
}
}
}
}
static class ThreadB extends Thread {
@Override
public void run() {
for (int i = 0; i < 10;) {
try {
lock.lock();
while (state % 3 == 1) {// 多線程併發,不能用if,必須用循環測試等待條件,避免虛假喚醒
System.out.print("B");
state++;
i++;
}
} finally {
lock.unlock();// unlock()操作必須放在finally塊中
}
}
}
}
static class ThreadC extends Thread {
@Override
public void run() {
for (int i = 0; i < 10;) {
try {
lock.lock();
while (state % 3 == 2) {// 多線程併發,不能用if,必須用循環測試等待條件,避免虛假喚醒
System.out.print("C");
state++;
i++;
}
} finally {
lock.unlock();// unlock()操作必須放在finally塊中
}
}
}
}
public static void main(String[] args) {
new ThreadA().start();
new ThreadB().start();
new ThreadC().start();
}
}
2.ReentrantLock搭配的通行方式是Condition,如下:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ABC_Condition {
private static Lock lock = new ReentrantLock();
private static Condition A = lock.newCondition();
private static Condition B = lock.newCondition();
private static Condition C = lock.newCondition();
private static int count = 0;
static class ThreadA extends Thread {
@Override
public void run() {
try {
lock.lock();
for (int i = 0; i < 10; i++) {
while (count % 3 != 0)//注意這裏是不等於0,也就是說在count % 3爲0之前,當前線程一直阻塞狀態
A.await(); // A釋放lock鎖
System.out.print("A");
count++;
B.signal(); // A執行完喚醒B線程
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
static class ThreadB extends Thread {
@Override
public void run() {
try {
lock.lock();
for (int i = 0; i < 10; i++) {
while (count % 3 != 1)
B.await();// B釋放lock鎖,當前面A線程執行後會通過B.signal()喚醒該線程
System.out.print("B");
count++;
C.signal();// B執行完喚醒C線程
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
static class ThreadC extends Thread {
@Override
public void run() {
try {
lock.lock();
for (int i = 0; i < 10; i++) {
while (count % 3 != 2)
C.await();// C釋放lock鎖
System.out.print("C");
count++;
A.signal();// C執行完喚醒A線程
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
new ThreadA().start();
new ThreadB().start();
new ThreadC().start();
}
}
參考:https://blog.csdn.net/qq_40664693/article/details/104916479
https://blog.csdn.net/xiaokang123456kao/article/details/77331878