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

java学习11--线程创建的两种方式,生命周期以及守护线程

2015-04-17 14:30 597 查看
1.线程分类:

1.用户线程 :执行在前台,完成具体任务

2守护线程:执行在后台,为其他前台线程服务。如果所有用户线程结束,守护线程没有需要守护的线程,会随着jvm结束工作。

常见守护线程:垃圾回收线程,数据库连接监测线程

2.线程创建

1.public class MyThread extends Thread

{

public void run()

{......

}

}

main()

{

MyThread mt=new MyThread();

mt.start();

}

2.public class MyTread implements Runnable

{

.....

}

main()

{

MyThread mt=new MyThread();

Thread th1=new Thread(mt,"xx");//这样可以共享mt中的成员变量,在票务系统开发中常用

Thread th2=new Thread(mt,"xxx");

th1.start();

th2.start();

}

优点:1.避免单继承 2.可以共享资源,如果是继承的话,会为每个线程创建相同的资源,不能达到共享

3.守护线程

守护线程中最好不要进行读写操作,因为一旦用户线程结束了,守护线程也结束,那么守护线程中的读写操作就终止了

示例:

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Scanner;

public class DaemonTest implements Runnable{

private String name;

public void run() {

// TODO Auto-generated method stub

System.out.print("守护线程开启"+Thread.currentThread().getName());

try {

writefile();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (Throwable e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.print("守护线程退出"+Thread.currentThread().getName());

}

public void writefile() throws IOException, Throwable

{

File file=new File("1.txt");

if(!file.exists())

{

file.createNewFile();

}

FileOutputStream out=new FileOutputStream(file);

for(int i=0;i<15;i++)

{

String str=i+"word";

out.write(str.getBytes());

Thread.sleep(1000);

System.out.println(str);

}

out.flush();

out.close();

}

public DaemonTest(String name)

{

this.name=name;

}

public static void main(String[] argvs)

{

System.out.println("主线程开始"+Thread.currentThread().getName());

DaemonTest dt=new DaemonTest("DaemonThread");

Thread thread=new Thread(dt);

thread.setDaemon(true);//设定为守护线程必须的语句,如果是继承线程类调用该函数,如果是接口实现就必须两步走

thread.start();

Scanner sc=new Scanner(System.in);

sc.next();

System.out.println("主线程结束"+Thread.currentThread().getName());//整个程序如果在守护线程读写时,我们从键盘中输入,就使得main线程任务完成了,守护线程
//的读写就终止了

}

}

4.线程生命周期

线程调用start方法,就绪状态只是意味着加入了线程队列,但不一定开始运行,只有获取了cpu的使用权才能够运行

运行时运行run方法,直到任务结束或者sleep方法等阻塞事件发生
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: