前言
这个问题在面试中经常被遇到,主要考察对线程的理解,以及多线程如何轮流占有等问题
关于该问题的一些相关知识可看我之前的文章
JUC高并发编程从入门到精通(全)
以及关于Thread的用法解析可看我之前的文章
java之Thread类详细分析(全)
java之Thread类实战模板(全)
线程间定制化通信
所谓定制化通信,需要让线程进行一定的顺序操作
案列:启动三个线程,按照如下要求:
AA打印5此,BB打印10次,CC打印15次,一共进行10轮
具体思路:
每个线程添加一个标志位,是该标志位则执行操作,并且修改为下一个标志位,通知下一个标志位的线程
创建一个可重入锁private Lock lock = new ReentrantLock();
分别创建三个开锁通知private Condition c1 = lock.newCondition();
具体资源类中的A线程代码操作
上锁,(执行具体操作(判断、操作、通知),解锁)放于try、finally
public void print5(int loop) throws InterruptedException {
//上锁
lock.lock();
try {
//判断
while(flag != 1) {
//等待
c1.await();
}
//干活
for (int i = 1; i <=5; i++) {
System.out.println(Thread.currentThread().getName()+" :: "+i+" :轮数:"+loop);
}
//通知
flag = 2; //修改标志位 2
c2.signal(); //通知BB线程
}finally {
//释放锁
lock.unlock();
}
}
资源类的其他线程操作也同理
具体完整代码
//第一步 创建资源类
class ShareResource {
//定义标志位
private int flag = 1; // 1 AA 2 BB 3 CC
//创建Lock锁
private Lock lock = new ReentrantLock();
//创建三个condition
private Condition c1 = lock.newCondition();
private Condition c2 = lock.newCondition();
private Condition c3 = lock.newCondition();
//打印5次,参数第几轮
public void print5(int loop) throws InterruptedException {
//上锁
lock.lock();
try {
//判断
while(flag != 1) {
//等待
c1.await();
}
//干活
for (int i = 1; i <=5; i++) {
System.out.println(Thread.currentThread().getName()+" :: "+i+" :轮数:"+loop);
}
//通知
flag = 2; //修改标志位 2
c2.signal(); //通知BB线程
}finally {
//释放锁
lock.unlock();
}
}
//打印10次,参数第几轮
public void print10(int loop) throws InterruptedException {
lock.lock();
try {
while(flag != 2) {
c2.await();
}
for (int i = 1; i <=10; i++) {
System.out.println(Thread.currentThread().getName()+" :: "+i+" :轮数:"+loop);
}
//修改标志位
flag = 3;
//通知CC线程
c3.signal();
}finally {
lock.unlock();
}
}
//打印15次,参数第几轮
public void print15(int loop) throws InterruptedException {
lock.lock();
try {
while(flag != 3) {
c3.await();
}
for (int i = 1; i <=15; i++) {
System.out.println(Thread.currentThread().getName()+" :: "+i+" :轮数:"+loop);
}
//修改标志位
flag = 1;
//通知AA线程
c1.signal();
}finally {
lock.unlock();
}
}
}
public class ThreadDemo3 {
public static void main(String[] args) {
ShareResource shareResource = new ShareResource();
new Thread(()->{
for (int i = 1; i <=10; i++) {
try {
shareResource.print5(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"AA").start();
new Thread(()->{
for (int i = 1; i <=10; i++) {
try {
shareResource.print10(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"BB").start();
new Thread(()->{
for (int i = 1; i <=10; i++) {
try {
shareResource.print15(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"CC").start();
}
}
代码截图
为了更好的铺垫,我们看其他的例子,如果是ABC各打印相关次数
正文
1. 通过synchronized的wait与notifyAll
public class test {
private static String message = "A";
private static Object lock = new Object();
public static void main(String[] args) {
new Thread(() -> {
int count = 1;
synchronized (lock) {
while (count < 101) {
while (!message.equals("A")) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(message);
message = "B";
count = count + 1;
lock.notifyAll();
}
}
},"A").start();
new Thread(() -> {
int count = 1;
synchronized (lock) {
while (count < 101) {
while (!message.equals("B")) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(message);
message = "C";
count = count + 1;
lock.notifyAll();
}
}
},"B").start();
new Thread(() -> {
int count = 1;
synchronized (lock) {
while (count < 101) {
while (!message.equals("C")) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(message);
message = "A";
count = count + 1;
lock.notifyAll();
}
}
},"C").start();
}
}
2. 通过线程不加锁定义状态变量
public class test {
private static String message = "A";
public static void main(String[] args) {
new Thread(() -> {
int count = 1;
while (count < 101) {
while (!message.equals("A")) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(message);
message = "B";
count = count + 1;
}
},"A").start();
new Thread(() -> {
int count = 1;
while (count < 101) {
while (!message.equals("B")) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(message);
message = "C";
count = count + 1;
}
},"B").start();
new Thread(() -> {
int count = 1;
while (count < 101) {
while (!message.equals("C")) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(message);
message = "A";
count = count + 1;
}
},"C").start();
}
}
3. 通过ReentrantLock的lock以及unlock
对于轮流打印有多种方式进行输出
也参考了网上的一些资料说明
友情链接:三线程按顺序交替打印ABC的四种方法
关于以上方法具体代码示例如下:
- try加锁,finally解锁
- 设置状态变量,通过每个线程的状态变量判断(先加锁,在判断状态变量,在解锁)
ThreadA extends Thread
之后重写run方法- 主函数 调用的时候通过
new ThreadA().start();
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class test {
static Lock lock = new ReentrantLock();// 通过JDK5中的Lock锁来保证线程的访问的互斥
private static int state = 1;//通过state的值来确定是否打印
static class ThreadA extends Thread {
@Override
public void run() {
for (int i = 0; i < 100;) {
try {
lock.lock();
while (state % 3 == 1) {// 多线程并发,不能用if,必须用循环测试等待条件,避免虚假唤醒
System.out.println("A");
state++;
i++;
}
} finally {
lock.unlock();// unlock()操作必须放在finally块中
}
}
}
}
static class ThreadB extends Thread {
@Override
public void run() {
for (int i = 0; i < 100;) {
try {
lock.lock();
while (state % 3 == 2) {
System.out.println("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 == 0) {
System.out.println("C");
state++;
i++;
}
} finally {
lock.unlock();// unlock()操作必须放在finally块中
}
}
}
}
public static void main(String[] args) {
new ThreadA().start();
new ThreadB().start();
new ThreadC().start();
}
}
4. ReentrantLock结合Condition
对于以下代码主要参考了如下资料:
三线程按顺序交替打印ABC的四种方法
Condition是被绑定到Lock上的,必须使用lock.newCondition()才能创建一个Condition
上了锁之后,才可以在锁内部中进行操作Condition A = lock.newCondition();
,在状态量不为0的时候,锁一直等待阻塞A.await()
,之后抢到了之后,通过B唤醒A的线程,使用B.signal();
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class test {
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 < 100; 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 < 100; 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 < 100; i++) {
while (count % 3 != 2)
C.await();// C释放lock锁,当前面B线程执行后会通过C.signal()唤醒该线程
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();
}
}
5. Semaphore信号量方式
定义的全局变量,使用static
通过static Semaphore A = new Semaphore(1);
,代表信号量为1
具体其代码块为:
-
semaphore.acquire(); 获取信号量
-
semaphore.release();释放信号量
import java.util.concurrent.Semaphore;
public class test {
// 以A开始的信号量,初始信号量数量为1
private static Semaphore A = new Semaphore(1);
// B、C信号量,A完成后开始,初始信号数量为0
private static Semaphore B = new Semaphore(0);
private static Semaphore C = new Semaphore(0);
static class ThreadA extends Thread {
@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
A.acquire();// A获取信号执行,A信号量减1,当A为0时将无法继续获得该信号量
System.out.print("A");
B.release();// B释放信号,B信号量加1(初始为0),此时可以获取B信号量
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class ThreadB extends Thread {
@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
B.acquire();
System.out.print("B");
C.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class ThreadC extends Thread {
@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
C.acquire();
System.out.println("C");
A.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
new ThreadA().start();
new ThreadB().start();
new ThreadC().start();
}
}