有以下需求:
兩個執行緒,需要列印字母和數字,格式A1B2C3 …
這個問題涉及到執行緒的等待,喚醒,執行緒間通信等知識,
下面看看實作代碼:
方法1:LockSupport
import java.util.concurrent.locks.LockSupport;
/**
* @author liming
* @date 2020/10
* @description 交替列印 A1B2C3 ...
*/
public class AlternatePrint {
static Thread t1 = null, t2 = null;
public static void main(String[] args) {
char[] aI = "1234567".toCharArray();
char[] aC = "ABCDEFG".toCharArray();
t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < aC.length; i++) {
// 起始先列印一個字母
System.out.println(aC[i]);
// 列印完喚醒t2列印數字
LockSupport.unpark(t2);
// 自己阻塞,等待喚醒
LockSupport.park();
}
}
});
t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < aI.length; i++) {
// 起始先阻塞等待
LockSupport.park();
// 被喚醒后列印數字
System.out.println(aI[i]);
// 喚醒t1
LockSupport.unpark(t1);
}
}
});
t1.start();
t2.start();
}
}
方法2:synchronized
import org.junit.Test;
/**
* @author liming
* @date 2020/10/14
* @description 交替列印 A1B2C3 ...
*/
public class AlternatePrint {
static Thread t1 = null, t2 = null;
/**
* 使用 synchronized
*/
@Test
public void alternatePrint() {
Object lock = new Object();
char[] aI = "1234567".toCharArray();
char[] aC = "ABCDEFG".toCharArray();
t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < aC.length; i++) {
synchronized (lock) {
System.out.println(aC[i]);
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < aI.length; i++) {
synchronized (lock) {
System.out.println(aI[i]);
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
t1.start();
t2.start();
}
}
測驗結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/172993.html
標籤:其他
上一篇:安全管理——訪問控制&用戶管理
