Java学习笔记——thread派生类的适用

来源:互联网 发布:淘宝地区下拉选择 编辑:程序博客网 时间:2024/06/05 07:42

在计算机中,线程可以说是最小的程序,主体活动是读取->处理->写入文件,对进程的考虑主要是并行的分配问题上,下面的程序通过具体设置线程休眠的时间来测试多线程的实现情况:

import java.io.*;public class TryThread extends Thread {/** * @param args */public TryThread(String firstName, String secondName, long delay) {this.firstName = firstName;this.secondName = secondName;aWhile = delay;/* * 所谓守护线程,是指在程序运行的时候在后台提供一种通用服务的线程,比如垃圾回收线程就是一个很称职的守护者, * 并且这种线程并不属于程序中不可或缺的部分。因此,当所有的非守护线程结束时,程序也就终止了,同时会杀死进程中的所有守护线程。 * 反过来说,只要任何非守护线程还在运行,程序就不会终止 */setDaemon(true);// setDaemon是将此进程标记为守护进程,如果设置为true则设置为守护进程,如果为false则为用户进程}public static void main(String[] args) {// TODO 自动生成方法存根Thread first = new TryThread("Hopalong", "Cassidy", 200L);Thread second = new TryThread("Marilyn", "Monroe", 300L);Thread third = new TryThread("Slim", "Pickens", 500L);System.out.println("Please Enter when you have had enough……\n");first.start();second.start();third.start();try {System.in.read();System.out.println("Enter pressed……\n");} catch (IOException e) {System.out.println(e);}System.out.println("Ending main()");return;}@Overridepublic void run() {try {while (true) {System.out.print(firstName);sleep(aWhile);//让此进程进入休眠,休眠时间为awileSystem.out.print(secondName + "\n");}} catch (InterruptedException e) {System.out.println(firstName + secondName + e);}}private String firstName;private String secondName;private long aWhile;}
实现结果如下:



0 0
原创粉丝点击