多线程练习-两个线程交替打印

【多线程练习-两个线程交替打印】
多线程的练习)

    • 两个线程交替打印
        • 使用syn 与notifyAll、wait实现
      • 使用lock实现

两个线程交替打印
一个打印数字,一个打印字符,两个字符配合一个字符; 如:1516H1718I1920J2122K2324L2526M2728N2930O3132P3334Q3536R3738S3940T4142U4344V4546W4748X4950Y5152Z

使用syn 与notifyAll、wait实现
//使用多线程交替打印 public class Main { publicstaticvoidmain(String [] args){ Object obj = new Object(); Thread printNum = new Thread(new PrintNum(obj)); Thread printChar = new Thread(new PrintChar(obj)); //printNum.setPriority(); printNum.start(); printChar.start(); } } class PrintChar implements Runnable{ private Object object ; public PrintChar(Object object){ this.object = object; } @Override public void run() { synchronized (object) { for (int i = 65; i <= 90; i++) { System.out.print((char) i); object.notifyAll(); try { object.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } class PrintNum implements Runnable{ private Object object; public PrintNum(Object object){ this.object=object; } @Override public void run() { synchronized (object){ for(int i=1; i<=52; i++){ System.out.print(i); if((i%2)==0){ object.notifyAll(); try { object.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }

使用lock实现
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Main {private Lock lock = new ReentrantLock(); private Condition printNum = lock.newCondition(); private Condition printchar = lock.newCondition(); public static void main(String[] args) { Main test = new Main(); Thread printNum = new Thread(test.new PrintNumt()); Thread printChar = new Thread(test.new PrintChart()); printChar.start(); printNum.start(); }//打印数字 class PrintNumt implements Runnable {@Override public void run() {for (int i = 1; i <= 52; i++) { lock.lock(); try { printchar.signalAll(); System.out.print(i); if (i % 2 == 0) { printNum.await(); } } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }}//打印字母 class PrintChart implements Runnable {@Override public void run() {for (int i = 0; i < 26; i++) { lock.lock(); try { printNum.signalAll(); System.out.print((char)(i + 'A')); printchar.await(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } }}} }

    推荐阅读