zoukankan      html  css  js  c++  java
  • 利用线程通信,写2个线程,一个线程打印1~52,另一个线程打印A~Z,打印顺序应该使12A34B56C···5152Z

    利用线程通信,写2个线程,一个线程打印1~52,另一个线程打印A~Z,打印顺序应该使12A34B56C···5152Z

    Object类提供了线程间通信的方法:wait()、notify()、notifyaAl(),它们是多线程通信的基础,而这种实现方式的思想自然是线程间通信。 

     1 public class ThreadTest06 {
     2     private boolean flag = true;
     3 
     4     /**
     5      * 打印两个连续的整数
     6      *
     7      * @throws InterruptedException
     8      */
     9     public synchronized void printNum() throws InterruptedException {
    10         for (int i = 1; i < 53; ) {
    11             if (!flag) {
    12                 wait();
    13             } else {
    14                 //两个i++放到这程序只需循环一次就可以了
    15                 //不放在for循环体里是防止线程唤醒后的多次叠加
    16                 System.out.print((i++) + "," + (i++) + ",");
    17                 flag = false;
    18                 notifyAll();
    19             }
    20         }
    21     }
    22 
    23     /**
    24      * 在两个整数之间打印一个字母
    25      *
    26      * @throws InterruptedException
    27      */
    28     public synchronized void printLetter() throws InterruptedException {
    29         for (int i = 1; i < 27; ) {
    30             if (flag) {
    31                 wait();
    32             } else {
    33                 System.out.print(i != 26 ? ((char) (i + 64) + ",") : ((char) (i + 64) + "\n"));
    34                 i++;
    35                 flag = true;
    36                 notifyAll();
    37             }
    38         }
    39     }
    40 
    41     public static void main(String[] args) {
    42         ThreadTest06 tt = new ThreadTest06();
    43 
    44         Runnable r1 = () -> {
    45             try {
    46                 tt.printNum();
    47             } catch (InterruptedException e) {
    48                 e.printStackTrace();
    49             }
    50         };
    51         Runnable r2 = () -> {
    52             try {
    53                 tt.printLetter();
    54             } catch (InterruptedException e) {
    55                 e.printStackTrace();
    56             }
    57         };
    58 
    59         new Thread(r1, "number").start();
    60         new Thread(r2, "letter").start();
    61     }
    62 }
  • 相关阅读:
    高斯消元学习
    HDU 4596 Yet another end of the world(解一阶不定方程)
    Codeforces Round #318 div2
    HDU 4463 Outlets(一条边固定的最小生成树)
    HDU 4458 Shoot the Airplane(计算几何 判断点是否在n边形内)
    HDU 4112 Break the Chocolate(简单的数学推导)
    HDU 4111 Alice and Bob (博弈)
    POJ 2481 Cows(线段树单点更新)
    HDU 4288 Coder(STL水过)
    zoj 2563 Long Dominoes
  • 原文地址:https://www.cnblogs.com/csl96/p/15669268.html
Copyright © 2011-2022 走看看