一,多线程的实现方式
方式一: 继承Thread类
/**
* Created by 阿越 on 2017/4/16.
*/
class myThread extends Thread {
private String name;
public myThread(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("线程" + name + "输出:" + i);
try {
sleep((int) Math.random() * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
myThread t1 = new myThread("A");
myThread t2 = new myThread("B");
t1.start();
t2.start();
}
}
方式二: 实现Runable接口(推荐)
/**
* Created by 阿越 on 2017/4/16.
*/
class myThread2 implements Runnable {
private String name;
public myThread2(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("线程" + name + "输出:" + i);
try {
Thread.sleep((int) Math.random() * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
new Thread(new myThread2("C")).start();
new Thread(new myThread2("D")).start();
}
}
二,两种方式的区别
最根本的区别:一种是继承扩展,而另一种是实现
三,实现Runnable接口比继承Thread类所具有的优势:
- 因为Java不支持多继承,但可以多实现,所以实现Runnable接口可以有效避免Java中单继承的限制。
- 线程池只能放入实现Runable或callable类线程,不能直接放入继承Thread的类
- 更容易实现线程间资源的共享,以卖书程序(假设书店只剩5本书)举例:
通过方式一继承Thread类来完成:
/**
* Created by 阿越 on 2017/4/16.
*/
class myThread extends Thread {
private String name;
// 只剩5本书
private int books = 5;
public myThread(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 5; i++) {
if (this.books > 0){
System.out.println("线程" + name + "卖了书,剩下books:" + (--this.books));
}
}
}
}
public class Main {
public static void main(String[] args) {
new myThread("A").start();
new myThread("B").start();
}
}
运行结果:
分析:启动两个线程来卖书,实际上,每个线程各卖了5本书,两个线程共卖了10本,但事实上书店只有5本书,每个线程都卖自己的书,没有达到资源的共享。
通过方式二实现Runnable接口来完成
/**
* Created by 阿越 on 2017/4/16.
*/
class myThread2 implements Runnable {
// 只剩5本书
private int books = 5;
public myThread2() {
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
if (this.books > 0) {
System.out.println("线程" + Thread.currentThread().getName() + "卖了书,剩下books:" + (--this.books));
}
}
}
}
public class Main {
public static void main(String[] args) {
myThread2 mt2 = new myThread2();
new Thread(mt2, "A").start();
new Thread(mt2, "B").start();
}
}
运行结果:
分析:同样是启动两个线程来卖书,但是,因为在线程中共享着同一个mt2(即同一个实现了Runnable接口的myThread2对象),所以即便多个线程在卖书,最后总共也只卖了5本书,达到资源的共享。