zoukankan      html  css  js  c++  java
  • Java 多线程编程

    1.synchronized/wait/notify

     1 package javamultithread;
     2 
     3 import java.util.logging.Level;
     4 import java.util.logging.Logger;
     5 
     6 /**
     7  *
     8  * @author Tina
     9  */
    10 public class Thread1 implements Runnable {
    11 
    12     private final Object current;
    13     private final Object next;
    14     private String name;
    15 
    16     public Thread1(String name, Object current, Object next) {
    17         this.name = name;
    18         this.current = current;
    19         this.next = next;
    20     }
    21 
    22     @Override
    23     public void run() {
    24         for (int i = 0; i < 10; i++) {
    25             synchronized (current) {
    26                 synchronized (next) {
    27                     System.out.print(name);
    28                     if (name.equalsIgnoreCase("C")) {
    29                         System.out.println();
    30                     }
    31                     next.notify();
    32                 }
    33                 if (i < 9) {
    34                     try {
    35                         current.wait();
    36                     } catch (InterruptedException ex) {
    37                         Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
    38                     }
    39                 }
    40             }
    41         }
    42     }
    43 
    44     public static void main(String[] args) {
    45         try {
    46             // TODO code application logic here
    47             Object o1 = new Object();
    48             Object o2 = new Object();
    49             Object o3 = new Object();
    50             Thread th1 = new Thread(new Thread1("A", o1, o2));
    51             Thread th2 = new Thread(new Thread1("B", o2, o3));
    52             Thread th3 = new Thread(new Thread1("C", o3, o1));
    53             th1.start();
    54             Thread.sleep(10);
    55             th2.start();
    56             Thread.sleep(10);
    57             th3.start();
    58             Thread.sleep(10);
    59         } catch (InterruptedException ex) {
    60             Logger.getLogger(JavaMultiThread.class
    61                     .getName()).log(Level.SEVERE, null, ex);
    62         }
    63 
    64     }
    65 }

    执行结果:

    run:
    ABC
    ABC
    ABC
    ABC
    ABC
    ABC
    ABC
    ABC
    ABC
    ABC
    成功构建 (总时间: 0 秒)
  • 相关阅读:
    SpringCloud教程五:Zuul(路由+过滤)
    ubuntu18.0.4 不能下载 libgd2-dev
    ubuntu18.04下安装中文输入法
    Ubuntu下tomcat启动报错:Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
    Java面试题汇总(一)
    Redis常见面试题
    Docker是什么
    Django实现自动发布(1数据模型)
    数据随机分配的思考
    单链表反转
  • 原文地址:https://www.cnblogs.com/tt2015-sz/p/5866554.html
Copyright © 2011-2022 走看看