Java中如何使用线程
2017-08-08 14:34
429 查看
首先了解线程的状态转换图:
在Java中一个类要当做线程来使用有两种方法:
1)继承Thread类,并重写run函数
2)实现Runnable接口,并重写run函数
Java是单继承的,但某些情况下一个类可能已经继承了某个父类,则不能再继承Thread类创建线程,只能用第二种。
下面是针对同一问题“编写一个程序,该程序每隔一秒自动输出Hello World,输出10次后自动退出”的两种不同方案。
方案一:
方案二:
在Java中一个类要当做线程来使用有两种方法:
1)继承Thread类,并重写run函数
2)实现Runnable接口,并重写run函数
Java是单继承的,但某些情况下一个类可能已经继承了某个父类,则不能再继承Thread类创建线程,只能用第二种。
下面是针对同一问题“编写一个程序,该程序每隔一秒自动输出Hello World,输出10次后自动退出”的两种不同方案。
方案一:
public class Demo_1 { public static void main(String[] args) { Cat cat=new Cat(); //创建一个Cat对象 cat.start(); //启动线程,会导致run()函数的运行 } } class Cat extends Thread{ int times=0; //重写run()函数 public void run(){ while(true){ //休眠一秒,1000表示1000毫秒,sleep就会让该线程进入Blocked状态,并释放资源 try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } times++; System.out.println("Hello World"+ times); if(times==10){ break; //退出 } } } }
方案二:
public class Demo_2 { public static void main(String[] args){ //注意启动 Dog dog=new Dog(); Thread t=new Thread(dog); t.start(); } } class Dog implements Runnable{ int times=0; public void run(){ while(true){ //休眠一秒 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } times++; System.out.println("Hello World"+times); if(times==10){ break; } } } }
相关文章推荐
- 进程和线程的关系,同时如何使用Java实现
- 编程技巧:在Java应用开发中如何使用线程
- java并发编程---如何创建线程以及Thread类的使用
- JAVA Eclipse中的Android程序如何使用线程
- Java核心知识点学习----线程中如何创建锁和使用锁 Lock,设计一个缓存系统
- Java学习笔记---------如何使用Runnable接口来创建线程???
- java学习——如何实现线程之间的通信 ,Condition 的使用
- 拿来主义:java中的线程安全与非线程安全,以及如何使用和实现
- JAVA Eclipse中的Android程序如何使用线程
- java线程中如何使用spring依赖注入
- 如何使用Java操作文本文件的方法详解 (转)
- 如何使用线程
- 如何使用J2ME中的线程
- 如何使用Java自带的正则表达式【转】
- Java中如何正确使用字体编码
- JAVA流使用总结——如何选择合适的流
- 如何使用Java编写多线程程序
- 如何使用Java POI生成Excel表文件
- 如何使用java程序界面上的按钮启动外部的exe程序
- 如何使用Java读取串口的程序