zoukankan      html  css  js  c++  java
  • Java笔记15:多线程

    Java实现多线程有两种方式:一是继承Thread类;二是实现Runable接口。

    一、Thread实现

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. publicclass ThreadDemo2 {  
    2.   
    3.     publicstaticvoid main(String[] args) {  
    4.   
    5.         new TestThread2().start();  
    6.   
    7.         inti = 0;  
    8.   
    9.         while(i++ < 100) {  
    10.   
    11.             System.out.println("main thread is running");  
    12.   
    13.         }  
    14.   
    15.     }  
    16.   
    17. }  
    18.   
    19.    
    20.   
    21. class TestThread2 extends Thread {  
    22.   
    23.     publicvoid run() {  
    24.   
    25.         intj = 0;  
    26.   
    27.         while(j++ < 100) {  
    28.   
    29.             System.out.println(Thread.currentThread().getName() + " is running!");  
    30.   
    31.         }  
    32.   
    33.     }  
    34.   
    35. }  

    运行结果:

     

    二、Runnable实现

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. publicclass ThreadDemo3 {  
    2.   
    3.     publicstaticvoid main(String[] args) {  
    4.   
    5.         TestThread3 t3 = new TestThread3();  
    6.   
    7.         Thread t = new Thread(t3);  
    8.   
    9.         t.start();  
    10.   
    11.         inti = 0;  
    12.   
    13.         while(i++ < 100) {  
    14.   
    15.             System.out.println("main thread is running");  
    16.   
    17.         }          
    18.   
    19.     }  
    20.   
    21. }  
    22.   
    23.    
    24.   
    25. class TestThread3 implements Runnable {  
    26.   
    27.     publicvoid run() {  
    28.   
    29.         intj = 0;  
    30.   
    31.         while(j++ < 100) {  
    32.   
    33.             System.out.println(Thread.currentThread().getName() + " is running!");  
    34.   
    35.         }  
    36.   
    37.     }  
    38.   
    39. }  

    运行结果:

     

  • 相关阅读:
    .NET Core 首例 Office 开源跨平台组件(NPOI Core)
    ASP.NET Core 导入导出Excel xlsx 文件
    python练习七—P2P下载
    VisualVM远程连接Tomcat
    一次Linux自动化部署尝试
    python练习六—简单的论坛
    shiro实现APP、web统一登录认证和权限管理
    python练习五—简单web应用
    python练习四—简单的聊天软件
    python练习三—解析xml
  • 原文地址:https://www.cnblogs.com/grimm/p/6732497.html
Copyright © 2011-2022 走看看