一捕捂,多線程的實(shí)現(xiàn)方式
方式一: 繼承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();
}
}
方式二: 實(shí)現(xiàn)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();
}
}
二瑟枫,兩種方式的區(qū)別
最根本的區(qū)別:一種是繼承擴(kuò)展,而另一種是實(shí)現(xiàn)
三绞蹦,實(shí)現(xiàn)Runnable接口比繼承Thread類所具有的優(yōu)勢(shì):
- 因?yàn)镴ava不支持多繼承力奋,但可以多實(shí)現(xiàn),所以實(shí)現(xiàn)Runnable接口可以有效避免Java中單繼承的限制幽七。
- 線程池只能放入實(shí)現(xiàn)Runable或callable類線程,不能直接放入繼承Thread的類
- 更容易實(shí)現(xiàn)線程間資源的共享溅呢,以賣書(shū)程序(假設(shè)書(shū)店只剩5本書(shū))舉例:
通過(guò)方式一繼承Thread類來(lái)完成:
/**
* Created by 阿越 on 2017/4/16.
*/
class myThread extends Thread {
private String name;
// 只剩5本書(shū)
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 + "賣了書(shū)澡屡,剩下books:" + (--this.books));
}
}
}
}
public class Main {
public static void main(String[] args) {
new myThread("A").start();
new myThread("B").start();
}
}
運(yùn)行結(jié)果:
Paste_Image.png
分析:?jiǎn)?dòng)兩個(gè)線程來(lái)賣書(shū),實(shí)際上咐旧,每個(gè)線程各賣了5本書(shū)驶鹉,兩個(gè)線程共賣了10本,但事實(shí)上書(shū)店只有5本書(shū)铣墨,每個(gè)線程都賣自己的書(shū)室埋,沒(méi)有達(dá)到資源的共享。
通過(guò)方式二實(shí)現(xiàn)Runnable接口來(lái)完成
/**
* Created by 阿越 on 2017/4/16.
*/
class myThread2 implements Runnable {
// 只剩5本書(shū)
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() + "賣了書(shū)伊约,剩下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();
}
}
運(yùn)行結(jié)果:
Paste_Image.png
分析:同樣是啟動(dòng)兩個(gè)線程來(lái)賣書(shū)姚淆,但是,因?yàn)樵诰€程中共享著同一個(gè)mt2(即同一個(gè)實(shí)現(xiàn)了Runnable接口的myThread2對(duì)象)屡律,所以即便多個(gè)線程在賣書(shū)腌逢,最后總共也只賣了5本書(shū),達(dá)到資源的共享超埋。