您的位置:首页 > 编程语言 > Java开发

Java中如何使用线程

2017-08-08 14:34 429 查看
首先了解线程的状态转换图:



在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;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: