多线程的编程支持是Java的一大特色
下边看一下多线程的实现
1、继承Thread类实现多线程
class Mythread extends Thread{
private String title;
public Mythread(String title) {
this.title = title;
}
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(this.title+"i = "+i);
}
}
}
public class Thread1 {
public static void main(String[] args) {
Mythread mythread1 = new Mythread("thread1");
Mythread mythread2 = new Mythread("thread2");
Mythread mythread3 = new Mythread("thread3");
mythread1.run();
mythread2.run();
mythread3.run();
}
}
这个时候只是做了一个顺序打印,和多线程一点关系都没有。正确启动多线程的方式是调用Thread类中的start()方
法。
启动多线程:public synchronized void start()此方法会自动调用线程的run()方法
正确启动多线程
/*
*继承Thread类实现多线程
*/
class Mythread extends Thread{
private String title;
public Mythread(String title) {
this.title = title;
}
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(this.title+"i = "+i);
}
}
}
public class Thread1 {
public static void main(String[] args) {
Mythread mythread1 = new Mythread("thread1");
Mythread mythread2 = new Mythread("thread2");
Mythread mythread3 = new Mythread("thread3");
mythread1.start();
mythread2.start();
mythread3.start();
}
}
此时再次执行代码发现,所有的线程对象变味了交替执行
可以通过eclipse查看start的源码
1. 首先我们看到在start()方法中抛出IllegalThreadStateException异常,按照原有的处理方式,应当在
调用处进行异常处理,而此处没有处理也不会报错,因此是一个RunTimeException,这个异常的产生
只是因为你重复启动了线程才会产生。所以,每一个线程对象只能够启动一次
2. 下面我们看到了在start()方法中调用了start0()方法,而这个方法是一个只声明而未实现的方法同时使用
native关键字进行定义。
在这我们需要说明下:
线程的调用是从start开始由start0到JVM中准备好资源然后在回调run方法的。
2、Runnable()接口实现多线程
Thread类的核心功能是进行线程的启动。如果一个类为了实现多线程直接去继承Thread类就会有但继承局限。在
java中又提供有另外一种实现模式:Runnable接口。
/*
* Runnable() 接口实现多线程
*/
class Mythread implements Runnable{
private String title;
public Mythread(String title) {
this.title = title;
}
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(this.title+" = "+i);
}
}
}
//启动多线程
public class Thread2 {
public static void main(String[] args) {
Mythread mythread1 = new Mythread("A");
Mythread mythread2 = new Mythread("B");
Mythread mythread3 = new Mythread("C");
new Thread(mythread1).start();
new Thread(mythread2).start();
new Thread(mythread3).start();
}
}