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 }

 

posted @ 2017-08-08 14:34  最咸的鱼  阅读(980)  评论(0编辑  收藏  举报