• java多线程-两个演员线程


    两个演员线程交替进行,一个直接继承Thread实现,另一个通过Runnable接口实现。

     1 package cn.test.muke;
     2 
     3 public class Actor extends Thread {
     4 
     5     @Override
     6     public void run() {
     7         System.out.println(getName() + "是一个演员!");
     8         int count = 0;
     9         boolean keepRunning = true;
    10         
    11         while(keepRunning) {
    12             System.out.println(getName() + "登台演出:" + (++count));
    13             
    14             if(count == 100) {
    15                 keepRunning = false;
    16             }
    17             
    18             if(count % 10 == 0) {
    19                 try {
    20                     Thread.sleep(1000);
    21                 } catch (InterruptedException e) {
    22                     // TODO Auto-generated catch block
    23                     e.printStackTrace();
    24                 }
    25             }
    26                 
    27         }
    28         
    29         System.out.println(getName() + "的演出结束了!");
    30     }
    31     
    32     public static void main(String args[]) {
    33         Thread actor = new Actor();
    34         actor.setName("Mr.Thread");
    35         
    36         actor.start();
    37         
    38         Thread actressThread = new Thread(new Actress(),"Ms.Runnable");
    39         actressThread.start();
    40     }
    41     
    42 }
    43 
    44 
    45 class Actress implements Runnable{
    46     
    47     @Override
    48     public void run() {
    49         System.out.println(Thread.currentThread().getName() + "是一个演员!");
    50         int count = 0;
    51         boolean keepRunning = true;
    52         
    53         while(keepRunning) {
    54             System.out.println(Thread.currentThread().getName() + "登台演出:" + (++count));
    55             
    56             if(count == 100) {
    57                 keepRunning = false;
    58             }
    59             
    60             if(count % 10 == 0) {
    61                 try {
    62                     Thread.sleep(1000);
    63                 } catch (InterruptedException e) {
    64                     // TODO Auto-generated catch block
    65                     e.printStackTrace();
    66                 }
    67             }
    68                 
    69         }
    70         
    71         System.out.println(Thread.currentThread().getName() + "的演出结束了!");
    72     }
    73 }
  • 相关阅读:
    条件变量:为什么要与互斥锁配套使用?为什么要使用while来避免虚假唤醒?
    【转】高性能IO之Reactor模式
    LeetCode127:单词接龙
    CF1245F: Daniel and Spring Cleaning
    权值线段树学习笔记
    luogu_4317: 花神的数论题
    luogu_2605: 基站选址
    入门平衡树: Treap
    CF1244C: The Football Season
    luogu_1156: 垃圾陷阱
  • 原文地址:https://www.cnblogs.com/fxw-learning/p/12331548.html
Copyright © 2020-2023  润新知