多线程中的sleep()
来源:互联网 发布:数据迁移 编辑:程序博客网 时间:2024/06/01 11:53
sleep()方法是Thread的一个方法,表示可以让一个线程进入睡眠,指定的时间,但是当达到指定时间之后并不会马上运行,
而是转到可运行状态,这是因为线程的调度机制再恢复线程的运行时也是需要时间的,
当一个对象调用了sleep()之后,并不会释放他所持有的对象的锁,所以不影响其他线程访问.
使用sleep()方法时必须要捕获异常 或抛出一个 InteruptedException异常.
实现线程的方式有两种:
- 继承java.lang.Thread,并重写它的run()方法,将线程的执行主体放入其中。
- 实现java.lang.Runnable接口,实现它的run()方法,并将线程的执行主体放入其中
1 run()方法:
package com;
public class MyThread extends Thread{
public void run(){
try{
System.out.println("run threadName="+this.currentThread().getName()+"begin");
Thread.sleep(5000);
System.out.println("run threadName="+this.currentThread().getName()+"end");
}catch(InterruptedException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
MyThread thread = new MyThread();
System.out.println("begin="+System.currentTimeMillis());
thread.run();
System.out.println("end="+System.currentTimeMillis());
}
}
输出 begin=1458183530490
run threadName=mainbegin
//睡眠5000毫秒
run threadName=mainend
end=1458183535491
start()方法:
package com;
public class MyThread extends Thread{
public void run(){
try{
System.out.println("run threadName="+this.currentThread().getName()+"begin");
Thread.sleep(5000);
System.out.println("run threadName="+this.currentThread().getName()+"end");
}catch(InterruptedException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
MyThread thread = new MyThread();
System.out.println("begin="+System.currentTimeMillis());
thread.start();
System.out.println("end="+System.currentTimeMillis());
}
}
输出 begin=1458183694347
end=1458183694348
run threadName=Thread-0begin
//睡眠5000毫秒
run threadName=Thread-0end
- 多线程中的sleep()
- 多线程中的sleep()
- Java sleep wait 在多线程中的区别
- 由sleep()谈多线程中的静态方法
- 多线程sleep
- 多线程----sleep
- Java中的多线程:sleep, wait, join 与 interrupt()的关系
- java多线程中的join()、 sleep()、 yield()、 wait()函数
- 深入理解Java多线程中的wait(),notify()和sleep()
- 【C#.37】多线程中的Sleep以及子线程优先级
- 多线程中的wait与sleep到底谁释放了锁
- java多线程中的sleep()方法与wait()方法的区别
- java 多线程中的sleep()与wait()方法的对比
- java中的多线程中wait和sleep方法的区别
- 深入理解Java多线程中的wait(),notify()和sleep()
- Android 多线程延迟(sleep)
- java 多线程sleep
- 多线程--sleep、yield对比
- ECharts-Java使用Java快速开发ECharts图表
- Spark1.0.0 运行架构基本概念
- VLC-DSS搭建直播系统中链路断开影响测试
- 策略路由基础命令(Linux)
- MySQL逻辑运算符 NULL运算结果
- 多线程中的sleep()
- Android Studio导入Eclipse的library工程
- Jetty和tomcat的比较
- Teaching the Next Generation of Statistics Students to “Think With Data”: Special Issue on Statistic
- ie8中一个很奇怪的现象。
- myeclipse trial expired
- 闭包
- DSS转发中sdp文件的简化
- 微软开放跨平台联机 索尼:我们早就这么做了