zoukankan      html  css  js  c++  java
  • JAVA 几种多线程的简单实例 Thread Runnable

    实例1:
    class Hello extends Thread{
    private String name;
    public Hello(){}
    public Hello(String name){
    this.name = name;
    }
    public void run(){
    for(int i=0;i<100;i++){
    System.out.println(this.name + i);
    }
    }
    public static void main(String[] args){
    Hello h1 = new Hello("A");
    Hello h2 = new Hello("B");
    h1.run();
    h2.run();
    }
    }
    
    这样的办法输出的结果会是顺序运行,不符合我们想要的多线程运行效果,接下来看 实例2:
    class Hello extends Thread{
    private String name;
    public Hello(){}
    public Hello(String name){
    this.name = name;
    }
    public void run(){
    for(int i=0;i<100;i++){
    System.out.println(this.name + i);
    }
    }
    public static void main(String[] args){
    Hello h1 = new Hello("A");
    Hello h2 = new Hello("B");
    h1.start();
    h2.start();
    }
    }
    
    实例3:
    class Hello implements Runnable{
    private String name;
    public Hello(){}
    public Hello(String name){
    this.name = name;
    }
    public void run(){
    for(int i=0;i<100;i++){
    System.out.println(this.name + i);
    }
    }
    public static void main(String[] args){
    Hello h1 = new Hello("A");
    Thread t1 = new Thread(h1);
    Hello h2 = new Hello("B");
    Thread t2 = new Thread(h2);
    t1.start();
    t2.start();
    }
    }
  • 相关阅读:
    Set和Multiset 怎么用咧↓↓↓
    sql server 复习笔记2
    sql server 复习笔记1
    数据分析相关学习 -1 numpy
    复习2
    scrapy 4 学习 crawl spider
    scrapy3 中间件的使用
    scapy2 爬取全站,以及使用post请求
    复习1
    scrapy 学习笔记2 数据持久化
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/7207746.html
Copyright © 2011-2022 走看看