提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
题目:编写3个线程,其中线程threadA打印1-52.线程threadB打印A-Z,线程threadC打印a-z打印顺序要求是12Aa34Bb—5152Zz
一、利用lock、Condition解决问题,实现Runnable接口。
一开始是可以想到用join()解决问题,但是join()执行过后,线程就死了。不能循环打印。
二、运行结果![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1e767286f99a81b72dcc13f5872bc492.png)
三、代码
代码如下(示例):
package test;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class T1 implements Runnable{
String name1;
String name2;
String name3;
private int num = 1;
private Lock lock = new ReentrantLock();//创建锁对象
private Condition condition1 = lock.newCondition();//条件1
private Condition condition2 = lock.newCondition();//条件2
private Condition condition3 = lock.newCondition();//条件3
T1(String n1,String n2,String n3){
this.name1=n1;
this.name2=n2;
this.name3=n3;
}
@Override
public void run() {
if(Thread.currentThread().getName().equals(name1)){
lock.lock();
while (num != 1){//这里jdk源码里推荐用while,因为有可能出现虚假唤醒,所以要再次确认
try {
condition1.await();//条件1线程等待,并释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num=2;
for(int i=1;i<=52;i++){
System.out.print(i);
if(i%2==0){
try {
condition2.signal();//总是唤醒2;
if (i != 52) {//i=52时表示为最后一次,所以不进入等待,以便让进程一死亡,确保程序自动结束,下面类似代码功能类似
condition1.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
lock.unlock();
}else if(Thread.currentThread().getName().equals(name2)){
lock.lock();
while (num != 2){//这里jdk源码里推荐用while,因为有可能出现虚假唤醒,所以要再次确认
try {
condition2.await();//条件2线程等待,并释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num=3;
for(int i=0;i<=25;i++){
System.out.print((char)('A'+i));
try {
condition3.signal();
if ((char) ('A' + i) != 'Z') {
condition2.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.unlock();
}else if(Thread.currentThread().getName().equals(name3)){
lock.lock();
while (num != 3){//这里jdk源码里推荐用while,因为有可能出现虚假唤醒,所以要再次确认
try {
condition3.await();//条件3线程等待,并释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num=1;
for(int i=0;i<=25;i++){
System.out.print((char)('a'+i));
try {
condition1.signal();
if ((char) ('a' + i) != 'z') {
condition3.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.unlock();
}
}
}
**
测试
**
package test;
public class Main {
public static void main(String[] args){
T1 t1=new T1("线程一","线程二","线程三");
Thread thread1=new Thread(t1,"线程一");
Thread thread2=new Thread(t1,"线程二");
Thread thread3=new Thread(t1,"线程三");
thread1.start();
try {
thread1.sleep(100);//延时,保证一开始的顺序正确
} catch (InterruptedException e) {
e.printStackTrace();
}
thread2.start();
try {
thread2.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread3.start();
try {
thread3.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}