开启两个线程,一个线程打印A~Z,一个线程打印1~52的数据
Posted ltb6w
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了开启两个线程,一个线程打印A~Z,一个线程打印1~52的数据相关的知识,希望对你有一定的参考价值。
开启两个线程,一个线程打印A~Z,一个线程打印1~52的数据
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class D20190803 private char a=‘A‘; private Lock lock = new ReentrantLock(); private Condition c_one=lock.newCondition(); private Condition c_two=lock.newCondition(); private static boolean flag=true; Thread letter=new Thread(new Runnable() public void run() for (int i=0;i<26;i++) lock.lock(); try if(flag) c_two.await(); System.out.print("【"+a+"】"); a++; Thread.sleep(100); flag=true; c_one.signal(); catch (InterruptedException e) e.printStackTrace(); finally lock.unlock(); ); Thread number=new Thread(new Runnable() public void run() for (int j=1;j<53;j++) lock.lock(); System.out.print(j+","); if(j%2==0 ) try Thread.sleep(100); c_two.signal(); flag=false; if(!flag) c_one.await(); catch (InterruptedException e) e.printStackTrace(); finally lock.unlock(); ); public static void main(String[] args) throws InterruptedException D20190803 d=new D20190803(); d.letter.start(); Thread.sleep(1000); d.number.start();
以上是关于开启两个线程,一个线程打印A~Z,一个线程打印1~52的数据的主要内容,如果未能解决你的问题,请参考以下文章
1.用两种方式实现两个线程,一个线程负责打印1-2600,另一个线程打印A-Z,反复打印10
使用A线程打印1-52,B线程打印A-Z,要求按照12A34B56C....5152Z的顺序进行交替打印