线程初步

来源:互联网 发布:梦幻西游2抓鬼经验算法 编辑:程序博客网 时间:2024/05/08 23:43
 
import java.io.IOException;public class CreateThread {public static void main(String[] args) {Thread first = new TryThread("三丰 " , "张  " , 2000L);Thread second = new TryThread("道子 ", "吴 ", 3000L);    Thread third = new TryThread("中山 ", "孙 ", 5000L);    System.out.println("开始运行啦,注意看结果....\n");    first.start();    second.start();    third.start();        try{    System.in.read();    System.out.println("EnterPress....\n");        }catch(IOException e){    e.printStackTrace();    }    return ;}}class TryThread extends Thread{private String firstName;private String secondName;private long aWhile;public TryThread(String firstName,String secondName,long delay){this.firstName = firstName;this.secondName = secondName;aWhile = delay;//delay:延时//将该线程标记为守护线程或用户线程。当正在运行的线程都是守护线程时,Java 虚拟机退出。 setDaemon(true);//daemon:守护进程}public void run(){try{while (true){System.out.print(firstName);sleep(aWhile);System.out.print(secondName + "\n");}}catch(InterruptedException e){System.out.println(firstName + secondName + e);}}}/** * 开始运行啦,注意看结果....三丰 道子 中山 张  三丰 吴 道子 张  三丰 孙 中山 吴 道子 张  三丰 张  三丰 吴 道子 张  三丰 孙 中山  */

public class ThreadDemo {public static void main(String[] args) {new NewThread();try{for(int i = 5; i > 0; i--){System.out.println("主线程" + i);Thread.sleep(1000);}}catch(InterruptedException e){System.out.println("主线程被打段");}System.out.println("退出主线程");}}class NewThread implements Runnable{Thread t;NewThread(){t = new Thread(this,"Demo");System.out.println("子线程:" + t);t.start();}public void run() {try{for(int i = 5; i > 0; i--){System.out.println("子线程" + i);Thread.sleep(500);}}catch(InterruptedException e){System.out.println("子线程被打段");}System.out.println("退出子线程");}}/**子线程:Thread[Demo,5,main]主线程5子线程5子线程4主线程4子线程3子线程2主线程3子线程1退出子线程主线程2主线程1退出主线程*/

原创粉丝点击