您的位置:首页 > 其它

关于实现多线程的相关问题

2013-06-16 02:57 302 查看
线程的实现有两种方式,一种是继承Thread类,一种是实现Runnable接口。

1.使用继承Thread方法实现多线程。

public class MyThread extends Thread{
private int time;        //线程的休眠时间
public MyThread(String name,int time){
super(name);        //设置线程名称
this.time = time;//设置线程时间
}
    public void run(){    //覆写run()方法
try{
Thead.sleep(this.time);//指定休眠时间
}catch(Exception e){
e.printStackTrace();
}
//输出信息
System.out.println(Thread.currentThread().getName()+"线程休眠"+this.time+"毫秒");
    }
}


public class ThreadDemo
{
public static void main(String args[]){
MyThread mt1 = new MyThread("线程1",10000);

MyThread mt2 = new MyThread("线程2",10000);

MyThread mt3 = new MyThread("线程3",10000);

mt1.start();
mt2.start();
mt3.start();
}
}


2.通过实现Runnable接口完成多线程操作。

public MyThread implements Runnable{
private String name;//线程名称
private int time;    //线程时间
public MyThread(String name,int time){
this.name = name;//设置线程名称
this.time = time;//设置线程时间
}
public void run(){//覆写run()方法
try{
Thread.sleep(this.time);//指定休眠时间
}catch(Exception e){
e.printStackTrace();
}
//输出信息
System.out.println(this.name+"线程休眠"+this.time+"毫秒");
}
}


public class ThreadDemo
{
public static void main(String args[]){
MyThread mt1 = new MyThread("线程1",10000);//实例一个线程对象,指定休眠时间

MyThread mt2 = new MyThread("线程2",20000);//实例一个线程对象,指定休眠时间

MyThread mt3 = new MyThread("线程3",30000);//实例一个线程对象,指定休眠时间

new Thread(mt1).start();//启动线程

new Thread(mt2).start();//启动线程

new Thread(mt3).start();//启动线程
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: