线程操作范例
来源:互联网 发布:股票预测算法 编辑:程序博客网 时间:2024/06/05 17:49
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启动线程 }}
0 0
- 线程操作范例
- 线程操作范例
- Java多线程--线程操作范例
- 线程池 范例
- python线程范例
- C# 操作 Word 范例
- Java操作XML范例
- javascript操作cookie范例
- 泛型操作范例
- javascript Xml操作范例
- 泛型操作范例
- MongoDB 操作范例
- hbase API操作范例
- linux crontab操作范例
- perl 操作excel范例
- git-hub操作范例
- SQL操作范例
- python 线程池使用范例
- apple 苹果官方的demo 下载地址
- php实现批量分批次链表更新
- 14.8.1 Overview of InnoDB Row Storage
- Log4j使用指南
- eclipse导入play项目
- 线程操作范例
- 修改tp-wr841n-v8的flash
- red hat官方的rhel操作系统版本号与内核版本号的对应关系
- Sys.WebForms.PageRequestManager 运行出现Sys未定义错误解决办法
- HDU 5587 Array
- 南大软院大神养成计划第十六天
- 【LeetCode】283Move Zeroes
- C-014.循环嵌套--九九乘法表
- C++文件操作