• Java中如何使用线程


    首先了解线程的状态转换图:

    在Java中一个类要当做线程来使用有两种方法:

    1)继承Thread类,并重写run函数

    2)实现Runnable接口,并重写run函数

    Java是单继承的,但某些情况下一个类可能已经继承了某个父类,则不能再继承Thread类创建线程,只能用第二种。

    下面是针对同一问题“编写一个程序,该程序每隔一秒自动输出Hello World,输出10次后自动退出”的两种不同方案。

    方案一:

     1 public class Demo_1 {
     2     public static void main(String[] args) {
     3         Cat cat=new Cat();        //创建一个Cat对象
     4         cat.start();              //启动线程,会导致run()函数的运行
     5     }
     6 }
     7 
     8 class Cat extends Thread{
     9     int times=0;
    10     //重写run()函数
    11     public void run(){
    12         while(true){                     
    13             //休眠一秒,1000表示1000毫秒,sleep就会让该线程进入Blocked状态,并释放资源
    14             try {
    15                 Thread.sleep(1000);
    16             } catch (InterruptedException e) {
    17                 // TODO Auto-generated catch block
    18                 e.printStackTrace();
    19             } 
    20             times++;
    21             System.out.println("Hello World"+ times);
    22             
    23             if(times==10){
    24                 break;       //退出
    25             }
    26         }    
    27     }
    28 }

    方案二:

     1 public class Demo_2 {
     2     public static void main(String[] args){
     3         //注意启动
     4         Dog dog=new Dog();
     5         Thread t=new Thread(dog);
     6         t.start();
     7     }
     8 }
     9 
    10 class Dog implements Runnable{
    11     int times=0;
    12     public void run(){
    13         while(true){
    14             //休眠一秒
    15             try {
    16                 Thread.sleep(1000);
    17             } catch (InterruptedException e) {
    18                 e.printStackTrace();
    19             }
    20             times++;
    21             System.out.println("Hello World"+times);
    22             
    23             if(times==10){
    24                 break;
    25             }
    26         }
    27     }
    28 }
  • 相关阅读:
    vue中表格自适应屏幕一屏显示
    css+jq实现星星评分
    CSS中width,min-width和max-width之间的联系
    用jq动态给导航菜单添加active
    解决ios中input兼容性问题
    swiper按钮点击无效及控制器无效问题
    bootstrap 模态框在iphone微信内点击无效
    vue,onerror实现当图片加载失败时使用默认图
    MVC模板页使用
    MVC框架+vue+elementUI
  • 原文地址:https://www.cnblogs.com/cxq1126/p/7306680.html
Copyright © 2020-2023  润新知