以前一直没接触过JAVA多线程编程,这几天学习下来感觉还蛮简单,可以轻松实现同步与互斥等问题,同时实现资源共享,减少了系统开销。
实现有2种方法:继承Thread类、实现runnable接口。而实际上,thread类也是实现了runnable接口,比如里面新添了name等属性。建议一般直接继承runnable接口。
以下是实现的2个简单的例子:
【1】、用第一种方法:
class MyThread extends Thread{
private int time ;
public MyThread(String name,int time){
super(name) ; // 设置线程名称
this.time = time ; // 设置休眠时间
}
public void 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",10000) ; // 定义线程对象,指定休眠时间
MyThread mt2 = new MyThread("线程B",20000) ; // 定义线程对象,指定休眠时间
MyThread mt3 = new MyThread("线程C",30000) ; // 定义线程对象,指定休眠时间
mt1.start() ; // 启动线程
mt2.start() ; // 启动线程
mt3.start() ; // 启动线程
}
};
【2】、用第二种方法
class MyThread implements Runnable{
private String name ;
private int time ;
public MyThread(String name,int time){
this.name = name ; // 设置线程名称
this.time = time ; // 设置休眠时间
}
public void run(){
try{
Thread.sleep(this.time) ; // 休眠指定的时间
}catch(InterruptedException e){
e.printStackTrace() ;
}
System.out.println(this.name + "线程,休眠"
+ this.time + "毫秒。") ;
}
};
public class ExecDemo02{
public static void main(String args[]){
MyThread mt1 = new MyThread("线程A",10000) ; // 定义线程对象,指定休眠时间
MyThread mt2 = new MyThread("线程B",20000) ; // 定义线程对象,指定休眠时间
MyThread mt3 = new MyThread("线程C",30000) ; // 定义线程对象,指定休眠时间
new Thread(mt1).start() ; // 启动线程
new Thread(mt2).start() ; // 启动线程
new Thread(mt3).start() ; // 启动线程
}
};