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启动线程
}
}