zoukankan      html  css  js  c++  java
  • 2016/1/25 多线程 作业 方法一 继承Thread 方法二 实现Runnable 多线程笔记

     1 /*
     2  * 1,尝试定义一个继承Thread类的类,并覆盖run()方法,
     3  * 在run()方法中每隔100毫秒打印一句话。*/
     4 package Stream;
     5 //方法一   继承Thread  实现多线程
     6 public class TestX extends Thread {
     7     public void run () {
     8         xiancheng();}
     9         public void xiancheng() 
    10         {
    11             for (int i = 0; i < 10; i++) {
    12                 System.out.println(this+"打印一句话"+i);
    13                 try {
    14                     Thread.sleep(100);//每100毫秒输出一次
    15                 } catch (InterruptedException e) {
    16                     // TODO 自动生成的 catch 块
    17                     e.printStackTrace();
    18                 }
    19             }
    20             
    21         }
    22     }
     1 package Stream;
     2 //方法二  实现Runnable 接口 
     3 public class TestXX  implements Runnable {
     4 
     5     @Override
     6     public void run() {
     7         duoxiancheng();
     8         }
     9     public void duoxiancheng() {
    10         for (int i = 0; i < 10; i++) {
    11             System.out.println("打印一句话"+i);
    12             try {
    13                 Thread.sleep(100);
    14             } catch (InterruptedException e) {
    15                 // TODO 自动生成的 catch 块
    16                 e.printStackTrace();
    17             }
    18         }
    19     }
    20 
    21     }
     1 package Stream;
     2 
     3 public class TestThread {
     4 
     5     
     6     public static void main(String[] args)  {
     7         TestX i=new TestX();
     8        i.start();
     9             
    10       TestX ii=new TestX();
    11       ii.start();
    12             
    13             
    14         
    15       TestXX s=new TestXX();
    16       Thread hh= new Thread(s);
    17       hh.start();
    18             
    19       TestXX ss=new TestXX();
    20       Thread hhs= new Thread(ss);
    21       hhs.start();
    22         
    23             
    24         }
    25 
    26     }

    上述显示三图  分别为  图一  两种方式一起输出  太长没有全截取     图二 为通过集成Thread实现多线程   图三为通过应用Runnable接口实现多线程

    多线程   笔记
             ①线程 进程里的执行流程
             ②实现方式 1,继承Thread 重写一个run()方法
                                使用start()方法启动多线程 同一时间只能
                                启动一个线程
                            2,实现Runnable接口 重写run()方法
                                调用Thread(Runnable)
                                调用Thread对象的start
            ③生命周期 出生状态
                           就绪状态
                           运行状态
                           等待状态
                           休眠状态
                           阻塞状态
                           死亡状态

  • 相关阅读:
    class7-附
    class6-附
    class6
    class5-附
    class4-附
    class4
    class3-附【家庭资产配置】
    class2
    芒果绿的blog
    java网络爬虫基础学习(四)
  • 原文地址:https://www.cnblogs.com/haodayikeshu/p/5158830.html
Copyright © 2011-2022 走看看