线程初步

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 退出主线程 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值