一、创建线程并启动
1、继承Thread类
1.1通过继承Thread类创建线程类的具体步骤和具体代码如下:
• 定义一个继承Thread类的子类,并重写该类的run()方法;
• 创建Thread子类的实例,即创建了线程对象;
• 调用该线程对象的start()方法启动线程。(不是run()方法)。
1.2利用Thread类的子类来创建就线程
public class MyClass {
public static void main(String [] args){
MyThread you=new MyThread("你");
MyThread she=new MyThread("他");
you.start(); //调用start()方法而不是run方法
she.start();
System.out.println("晚安");
}
}
class MyThread extends Thread{ //创建Thread类的子类MyThread
private String who;
public MyThread(String who){ //构造方法,用于设置成员变量who
this.who=who;
}
public void run() { //覆盖Thread类里的run()方法
for (int i = 0; i < 5; i++) {
try {
sleep((int)(1000*Math.random()));//控制线程睡眠时间为0~1秒间的浮点型随机数
} catch (InterruptedException e) {
System.out.println(e.toString());
}
System.out.println(who + "在运行");
}
}
}
输出:
晚安 //Main函数是主线程,所以会优先执行
你在运行
他在运行
他在运行
你在运行
你在运行
你在运行
他在运行
你在运行
他在运行
他在运行
Process finished with exit code 0
2、实现Runnable接口
2.1通过实现Runnable接口创建线程类的具体步骤和具体代码如下:
• 定义Runnable接口的实现类,并重写该接口的run()方法;
• 创建Runnable实现类的实例,并以此实例作为Thread的target对象,即该Thread对象才是真正的线程对象。
2.2利用Runnable接口来创建线程
public class MyClass {
public static void main(String [] args){
MyThread you=new MyThread("你");
MyThread she=new MyThread("他");
Thread t1=new Thread(you); //产生Thread类的对象t1
Thread t2=new Thread(she); //产生Thread类的对象t2
t1.start();
t2.start();
System.out.println("晚安");
}
}
class MyThread implements Runnable{ //由Runnable接口实现MyThread类
private String who;
public MyThread(String who){
this.who=who;
}
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep((int)(1000*Math.random())); //sleep前要加前缀Thread
} catch (InterruptedException e) {
System.out.println(e.toString());
}
System.out.println(who + "在运行");
}
}
}
输出:
晚安
他在运行
你在运行
你在运行
他在运行
他在运行
你在运行
他在运行
他在运行
你在运行
你在运行
Process finished with exit code 0
二、join()方法
暂停当前线程的执行,等待调用该方法的线程结束后再继续执行本线程
在前面的例子可以看出程序中被同时激活的多个线程将同时执行,但有时需要有序执行,这时可以使用Thread类中的join()方法。当某一线程调用join()方法时,则其他线程会等到该线程结束后才开始执行
在多线程中join()方法的使用
public class MyClass {
public static void main(String [] args){
MyThread you=new MyThread("你");
MyThread she=new MyThread("他");
Thread t1=new Thread(you);
Thread t2=new Thread(she);
t1.start();
try {
t1.join();
}catch (InterruptedException e){}
t2.start();
try {
t2.join();
}catch (InterruptedException e){
}
System.out.println("晚安");
}
}
class MyThread implements Runnable{
private String who;
public MyThread(String who){
this.who=who;
}
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep((int)(1000*Math.random()));
} catch (InterruptedException e) {
System.out.println(e.toString());
}
System.out.println(who + "在运行");
}
}
}
输出:
你在运行
你在运行
你在运行
你在运行
你在运行
他在运行
他在运行
他在运行
他在运行
他在运行
晚安
Process finished with exit code 0
三、小结
通过上面的介绍,我们知道了由两种创建线程对象的方法。且各有特点
·直接继承Thread类的特点是:
编写简单,可以直接操纵线程;但缺点是若继承Thread类,就不能再继承其他类。
·使用Runnable接口的特点是:
可以将Thread类与所要处理的人物的类分开,形成清晰的模型,还可以从其他类继承,从而实现多重继承的功能。
·另外
若直接使用Thread类,在类中this即指当前线程;若使用Runnable接口,要在此类中获得当前线程,必须使用Thread.currentThread()方法。