线程操作范例
2015-12-01 13:29
204 查看
1.1 使用 Thread 类
在Thread中直接存在了name属性,class MyThread extends Thread { public int time ; //设置时间属性 public MyThread(String name,int time) //Thread类中有name属性 { super(name) ; //为name属性赋值 this.time = time ; //设置休眠时间 } public void run() //覆写run()方法 { try { Thread.sleep(this.time) ;//休眠指定的时间 } catch (InterruptedException e) { e.printStackTrace() ; } System.out.println(Thread.currentThread().getName() +"线程,休眠"+this.time+"毫秒") ; } } public class ExecDemo01 { public static void main(String[] args) { MyThread mt1 = new MyThread("线程A",2000) ; MyThread mt2 = new MyThread("线程B",3000) ; mt1.start() ; //启动线程 mt2.start() ; //启动线程 } }
1.2 使用Runnable接口
如果使用Runnable接口,则类中是不存在线程名称的,需要单独创建一个name属性,以保存线程名称。
而且启动线程的时候 使用 new Thread(类对象).start()
class MyThread implements Runnable { public String name ; //接口中没有name属性,需要建立一个 以保存线程名称 public int time ; //设置时间属性 public MyThread(String name,int time) //Thread类中有name属性 { this.name = name ; //为name属性赋值 this.time = time ; //设置休眠时间 } public void run() //覆写run()方法 { try { Thread.sleep(this.time) ;//休眠指定的时间 } catch (InterruptedException e) { e.printStackTrace() ; } System.out.println(this.name+"线程,休眠"+this.time+"毫秒") ; } } public class ExecDemo01 { public static void main(String[] args) { MyThread mt1 = new MyThread("线程A",2000) ; MyThread mt2 = new MyThread("线程B",3000) ; new Thread(mt1).start() ; //new Thread(类对象).start() new Thread(mt2).start() ; //n启动线程 } }
相关文章推荐
- 南大软院大神养成计划第十六天
- Autofac 解释第一个例子 《第一篇》
- Log4j使用指南
- js base64位和c# Base64位转换
- php中session_start()函数的作用
- php实现批量分批次链表更新
- js数组操作大全(pop,push,unshift,splice,shift方法)
- 14.8.1 Overview of InnoDB Row Storage
- linux上mysql远程备份和自动导入到指定数据库的shell脚本
- hadoop 2.2 错误总结
- @RequiresPermissions 解释
- poj1363--Rails解题报告(c++版)
- 如何写好 Git Commit 信息
- 浮点数保存格式
- block,inline和inline-block概念和区别
- jquery-qrcode生成二维码
- 每天一个linux命令(54):sftp命令
- SRAM与DRAM
- struts2笔试面试
- Execution failed for task ':app:processDebugManifest'