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 秒)
  • 相关阅读:
    hdu 2604 Queuing(矩阵快速幂乘法)
    hdu 5591 ZYB's Game
    hdu 5590 ZYB's Biology
    CodeForces
    uva 193 Graph Coloring(图染色 dfs回溯)
    uva 10004 Bicoloring(dfs二分染色,和hdu 4751代码差不多)
    CSU
    hdu 5115 Dire Wolf(区间dp)
    腾讯装扮下拉选项卡特效(QQ空间)
    楼梯式定位导航系统
  • 原文地址:https://www.cnblogs.com/tt2015-sz/p/5866554.html
Copyright © 2011-2022 走看看