
package com.vince;
/**
*线程的休眠
* 在当前线程的执行中,暂停指定的毫秒数,释放CPU时间片
* millis:以毫秒为单位的睡眠时间长度
* InterruptedException:如果任何线程中断当前线程,当抛出此异常时,当前线程的中断状态将被清除
* Thread.currentThread(): 获取当前线程
* */
/**
* 继承Thread: 有开辟线程的能力,资源共享方面不是很方便。
* 实现runable接口: 没有开辟线程的能力,要将创建的对象交给指定线程来运行
*/
public class ThreadDemo1 {
public static void main(String[] args) {
MyThread mt = new MyThread();
//推荐
MyRunnable mr = new MyRunnable();
Thread tr = new Thread(mr);
mt.start(); //启动线程
tr.start();
}
}
//实现线程的一种方式,继承Thread类
class MyThread extends Thread{
@Override
public void run() {
for(int i =0; i <= 5; i++ ){
System.out.println(Thread.currentThread().getName()+"-"+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//另一种方式,实现Runnnable接口
class MyRunnable implements Runnable{
@Override
public void run() {
for(int i =0; i <= 5; i++ ){
System.out.println(Thread.currentThread().getName()+"-"+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pzMTM0MjA4NDc3Ng_size_16_color_FFFFFF_t_70][]
还没有评论,来说两句吧...