在 java 中要想實現(xiàn)多線程,有兩種手段,一種是繼續(xù) Thread 類,另外一種是實現(xiàn) Runable 接口。
對于直接繼承 Thread 的類來說,代碼大致框架是:
class 類名 extends Thread{
方法1;
方法2;
…
public void run(){
// other code…
}
屬性1;
屬性2;
…
}
先看一個簡單的例子:
/**
* @author Rollen-Holt 繼承Thread類,直接調(diào)用run方法
* */
class hello extends Thread {
public hello() {
}
public hello(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + "運行 " + i);
}
}
public static void main(String[] args) {
hello h1=new hello("A");
hello h2=new hello("B");
h1.run();
h2.run();
}
private String name;
}
【運行結(jié)果】:
A 運行 0
A 運行 1
A 運行 2
A 運行 3
A 運行 4
B 運行 0
B 運行 1
B 運行 2
B 運行 3
B 運行 4
我們會發(fā)現(xiàn)這些都是順序執(zhí)行的,說明我們的調(diào)用方法不對,應(yīng)該調(diào)用的是 start()方法。
當(dāng)我們把上面的主函數(shù)修改為如下所示的時候:
public static void main(String[] args) {
hello h1=new hello("A");
hello h2=new hello("B");
h1.start();
h2.start();
}
然后運行程序,輸出的可能的結(jié)果如下:
A 運行 0
B 運行 0
B 運行 1
B 運行 2
B 運行 3
B 運行 4
A 運行 1
A 運行 2
A 運行 3
A 運行 4
因為需要用到 CPU 的資源,所以每次的運行結(jié)果基本是都不一樣的,呵呵。
注意:雖然我們在這里調(diào)用的是 start()方法,但是實際上調(diào)用的還是 run()方法的主體。
那么:為什么我們不能直接調(diào)用 run()方法呢?
我的理解是:線程的運行需要本地操作系統(tǒng)的支持。
如果你查看 start 的源代碼的時候,會發(fā)現(xiàn):
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0 || this != me)
throw new IllegalThreadStateException();
group.add(this);
start0();
if (stopBeforeStart) {
stop0(throwableFromStop);
}
}
private native void start0();
注意我用紅色加粗的那一條語句,說明此處調(diào)用的是 start0()。并且這個這個方法用了 native 關(guān)鍵字,次關(guān)鍵字表示調(diào)用本地操作系統(tǒng)的函數(shù)。因為多線程的實現(xiàn)需要本地操作系統(tǒng)的支持。
但是 start 方法重復(fù)調(diào)用的話,會出現(xiàn) java.lang.IllegalThreadStateException 異常。
通過實現(xiàn) Runnable 接口:
大致框架是:
class 類名 implements Runnable{
方法1;
方法2;
…
public void run(){
// other code…
}
屬性1;
屬性2;
…
}
來先看一個小例子吧:
/**
* @author Rollen-Holt 實現(xiàn)Runnable接口
* */
class hello implements Runnable {
public hello() {
}
public hello(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + "運行 " + i);
}
}
public static void main(String[] args) {
hello h1=new hello("線程A");
Thread demo= new Thread(h1);
hello h2=new hello("線程B");
Thread demo1=new Thread(h2);
demo.start();
demo1.start();
}
private String name;
}
【可能的運行結(jié)果】:
線程 A 運行 0
線程 B 運行 0
線程 B 運行 1
線程 B 運行 2
線程 B 運行 3
線程 B 運行 4
線程 A 運行 1
線程 A 運行 2
線程 A 運行 3
線程 A 運行 4
關(guān)于選擇繼承 Thread 還是實現(xiàn) Runnable 接口?
其實 Thread 也是實現(xiàn) Runnable 接口的:
class Thread implements Runnable {
//…
public void run() {
if (target != null) {
target.run();
}
}
}
其實 Thread 中的 run 方法調(diào)用的是 Runnable 接口的 run 方法。不知道大家發(fā)現(xiàn)沒有, Thread 和 Runnable 都實現(xiàn)了 run 方法,這種操作模式其實就是代理模式。關(guān)于代理模式,我曾經(jīng)寫過一個小例子呵呵,大家有興趣的話可以看一下:http://www.cnblogs.com/rollenholt/archive/2011/08/18/2144847.html
Thread 和 Runnable 的區(qū)別:
如果一個類繼承 Thread,則不適合資源共享。但是如果實現(xiàn)了 Runable 接口的話,則很容易的實現(xiàn)資源共享。
/**
* @author Rollen-Holt 繼承Thread類,不能資源共享
* */
class hello extends Thread {
public void run() {
for (int i = 0; i < 7; i++) {
if (count > 0) {
System.out.println("count= " + count--);
}
}
}
public static void main(String[] args) {
hello h1 = new hello();
hello h2 = new hello();
hello h3 = new hello();
h1.start();
h2.start();
h3.start();
}
private int count = 5;
}
【運行結(jié)果】:
count= 5
count= 4
count= 3
count= 2
count= 1
count= 5
count= 4
count= 3
count= 2
count= 1
count= 5
count= 4
count= 3
count= 2
count= 1
大家可以想象,如果這個是一個買票系統(tǒng)的話,如果 count 表示的是車票的數(shù)量的話,說明并沒有實現(xiàn)資源的共享。
我們換為 Runnable 接口
class MyThread implements Runnable{
private int ticket = 5; //5張票
public void run() {
for (int i=0; i<=20; i++) {
if (this.ticket > 0) {
System.out.println(Thread.currentThread().getName()+ "正在賣票"+this.ticket--);
}
}
}
}
public class lzwCode {
public static void main(String [] args) {
MyThread my = new MyThread();
new Thread(my, "1號窗口").start();
new Thread(my, "2號窗口").start();
new Thread(my, "3號窗口").start();
}
}
【運行結(jié)果】:
count= 5
count= 4
count= 3
count= 2
count= 1
總結(jié)一下吧:
實現(xiàn) Runnable 接口比繼承 Thread 類所具有的優(yōu)勢:
1):適合多個相同的程序代碼的線程去處理同一個資源
2):可以避免 java 中的單繼承的限制
3):增加程序的健壯性,代碼可以被多個線程共享,代碼和數(shù)據(jù)獨立。
所以,本人建議大家勁量實現(xiàn)接口。
/**
* @author Rollen-Holt
* 取得線程的名稱
* */
class hello implements Runnable {
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String[] args) {
hello he = new hello();
new Thread(he,"A").start();
new Thread(he,"B").start();
new Thread(he).start();
}
}
【運行結(jié)果】:
A
A
A
B
B
B
Thread-0
Thread-0
Thread-0
說明如果我們沒有指定名字的話,系統(tǒng)自動提供名字。
提醒一下大家:main 方法其實也是一個線程。在 java 中所以的線程都是同時啟動的,至于什么時候,哪個先執(zhí)行,完全看誰先得到 CPU 的資源。
在 java 中,每次程序運行至少啟動2個線程。一個是 main 線程,一個是垃圾收集線程。因為每當(dāng)使用 java 命令執(zhí)行一個類的時候,實際上都會啟動一個 JVM,每一個 JVM 實習(xí)在就是在操作系統(tǒng)中啟動了一個進程。
判斷線程是否啟動
/**
* @author Rollen-Holt 判斷線程是否啟動
* */
class hello implements Runnable {
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String[] args) {
hello he = new hello();
Thread demo = new Thread(he);
System.out.println("線程啟動之前---》" + demo.isAlive());
demo.start();
System.out.println("線程啟動之后---》" + demo.isAlive());
}
}
【運行結(jié)果】
線程啟動之前---》false
線程啟動之后---》true
Thread-0
Thread-0
Thread-0
主線程也有可能在子線程結(jié)束之前結(jié)束。并且子線程不受影響,不會因為主線程的結(jié)束而結(jié)束。
線程的強制執(zhí)行:
/**
* @author Rollen-Holt 線程的強制執(zhí)行
* */
class hello implements Runnable {
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String[] args) {
hello he = new hello();
Thread demo = new Thread(he,"線程");
demo.start();
for(int i=0;i<50;++i){
if(i>10){
try{
demo.join(); //強制執(zhí)行demo
}catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("main 線程執(zhí)行-->"+i);
}
}
}
【運行的結(jié)果】:
main 線程執(zhí)行-->0
main 線程執(zhí)行-->1
main 線程執(zhí)行-->2
main 線程執(zhí)行-->3
main 線程執(zhí)行-->4
main 線程執(zhí)行-->5
main 線程執(zhí)行-->6
main 線程執(zhí)行-->7
main 線程執(zhí)行-->8
main 線程執(zhí)行-->9
main 線程執(zhí)行-->10
線程
線程
線程
main 線程執(zhí)行-->11
main 線程執(zhí)行-->12
main 線程執(zhí)行-->13
...
線程的休眠:
/**
* @author Rollen-Holt 線程的休眠
* */
class hello implements Runnable {
public void run() {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + i);
}
}
public static void main(String[] args) {
hello he = new hello();
Thread demo = new Thread(he, "線程");
demo.start();
}
}
【運行結(jié)果】:(結(jié)果每隔 2 s 輸出一個)
線程0
線程1
線程2
線程的中斷:
/**
* @author Rollen-Holt 線程的中斷
* */
class hello implements Runnable {
public void run() {
System.out.println("執(zhí)行run方法");
try {
Thread.sleep(10000);
System.out.println("線程完成休眠");
} catch (Exception e) {
System.out.println("休眠被打斷");
return; //返回到程序的調(diào)用處
}
System.out.println("線程正常終止");
}
public static void main(String[] args) {
hello he = new hello();
Thread demo = new Thread(he, "線程");
demo.start();
try{
Thread.sleep(2000);
}catch (Exception e) {
e.printStackTrace();
}
demo.interrupt(); //2s后中斷線程
}
}
【運行結(jié)果】:
執(zhí)行 run 方法
休眠被打斷
在 java 程序中,只要前臺有一個線程在運行,整個 java 程序進程不會小時,所以此時可以設(shè)置一個后臺線程,這樣即使 java 進程小時了,此后臺線程依然能夠繼續(xù)運行。
/**
* @author Rollen-Holt 后臺線程
* */
class hello implements Runnable {
public void run() {
while (true) {
System.out.println(Thread.currentThread().getName() + "在運行");
}
}
public static void main(String[] args) {
hello he = new hello();
Thread demo = new Thread(he, "線程");
demo.setDaemon(true);
demo.start();
}
}
雖然有一個死循環(huán),但是程序還是可以執(zhí)行完的。因為在死循環(huán)中的線程操作已經(jīng)設(shè)置為后臺運行了。
線程的優(yōu)先級:
/**
* @author Rollen-Holt 線程的優(yōu)先級
* */
class hello implements Runnable {
public void run() {
for(int i=0;i<5;++i){
System.out.println(Thread.currentThread().getName()+"運行"+i);
}
}
public static void main(String[] args) {
Thread h1=new Thread(new hello(),"A");
Thread h2=new Thread(new hello(),"B");
Thread h3=new Thread(new hello(),"C");
h1.setPriority(8);
h2.setPriority(2);
h3.setPriority(6);
h1.start();
h2.start();
h3.start();
}
}
【運行結(jié)果】:
A 運行0
A 運行1
A 運行2
A 運行3
A 運行4
B 運行0
C 運行0
C 運行1
C 運行2
C 運行3
C 運行4
B 運行1
B 運行2
B 運行3
B 運行4
但是請讀者不要誤以為優(yōu)先級越高就先執(zhí)行。誰先執(zhí)行還是取決于誰先去的 CPU 的資源、
另外,主線程的優(yōu)先級是5.
線程的禮讓。
在線程操作中,也可以使用 yield()方法,將一個線程的操作暫時交給其他線程執(zhí)行。
/**
* @author Rollen-Holt 線程的優(yōu)先級
* */
class hello implements Runnable {
public void run() {
for(int i=0;i<5;++i){
System.out.println(Thread.currentThread().getName()+"運行"+i);
if(i==3){
System.out.println("線程的禮讓");
Thread.currentThread().yield();
}
}
}
public static void main(String[] args) {
Thread h1=new Thread(new hello(),"A");
Thread h2=new Thread(new hello(),"B");
h1.start();
h2.start();
}
}
A 運行0
A 運行1
A 運行2
A 運行3
線程的禮讓
A 運行4
B 運行0
B 運行1
B 運行2
B 運行3
線程的禮讓
B 運行4
同步和死鎖:
【問題引出】:比如說對于買票系統(tǒng),有下面的代碼:
/**
* @author Rollen-Holt
* */
class hello implements Runnable {
public void run() {
for(int i=0;i<10;++i){
if(count>0){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(count--);
}
}
}
public static void main(String[] args) {
hello he=new hello();
Thread h1=new Thread(he);
Thread h2=new Thread(he);
Thread h3=new Thread(he);
h1.start();
h2.start();
h3.start();
}
private int count=5;
}
【運行結(jié)果】:
5
4
3
2
1
0
-1
這里出現(xiàn)了-1,顯然這個是錯的。,應(yīng)該票數(shù)不能為負(fù)值。
如果想解決這種問題,就需要使用同步。所謂同步就是在統(tǒng)一時間段中只有有一個線程運行,
其他的線程必須等到這個線程結(jié)束之后才能繼續(xù)執(zhí)行。
【使用線程同步解決問題】
采用同步的話,可以使用同步代碼塊和同步方法兩種來完成。
【同步代碼塊】:
語法格式:
synchronized(同步對象){
//需要同步的代碼
}
但是一般都把當(dāng)前對象 this 作為同步對象。
比如對于上面的買票的問題,如下:
/**
* @author Rollen-Holt
* */
class hello implements Runnable {
public void run() {
for(int i=0;i<10;++i){
synchronized (this) {
if(count>0){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(count--);
}
}
}
}
public static void main(String[] args) {
hello he=new hello();
Thread h1=new Thread(he);
Thread h2=new Thread(he);
Thread h3=new Thread(he);
h1.start();
h2.start();
h3.start();
}
private int count=5;
}
【運行結(jié)果】:(每一秒輸出一個結(jié)果)
5
4
3
2
1
【同步方法】
也可以采用同步方法。
語法格式為
synchronized 方法返回類型方法名(參數(shù)列表){
// 其他代碼
}
現(xiàn)在,我們采用同步方法解決上面的問題。
/**
* @author Rollen-Holt
* */
class hello implements Runnable {
public void run() {
for (int i = 0; i < 10; ++i) {
sale();
}
}
public synchronized void sale() {
if (count > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(count--);
}
}
public static void main(String[] args) {
hello he = new hello();
Thread h1 = new Thread(he);
Thread h2 = new Thread(he);
Thread h3 = new Thread(he);
h1.start();
h2.start();
h3.start();
}
private int count = 5;
}
【運行結(jié)果】(每秒輸出一個)
5
4
3
2
1
提醒一下,當(dāng)多個線程共享一個資源的時候需要進行同步,但是過多的同步可能導(dǎo)致死鎖。
此處列舉經(jīng)典的生產(chǎn)者和消費者問題。
【生產(chǎn)者和消費者問題】
先看一段有問題的代碼。
class Info {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private String name = "Rollen";
private int age = 20;
}
/**
* 生產(chǎn)者
* */
class Producer implements Runnable{
private Info info=null;
Producer(Info info){
this.info=info;
}
public void run(){
boolean flag=false;
for(int i=0;i<25;++i){
if(flag){
this.info.setName("Rollen");
try{
Thread.sleep(100);
}catch (Exception e) {
e.printStackTrace();
}
this.info.setAge(20);
flag=false;
}else{
this.info.setName("chunGe");
try{
Thread.sleep(100);
}catch (Exception e) {
e.printStackTrace();
}
this.info.setAge(100);
flag=true;
}
}
}
}
/**
* 消費者類
* */
class Consumer implements Runnable{
private Info info=null;
public Consumer(Info info){
this.info=info;
}
public void run(){
for(int i=0;i<25;++i){
try{
Thread.sleep(100);
}catch (Exception e) {
e.printStackTrace();
}
System.out.println(this.info.getName()+"<---->"+this.info.getAge());
}
}
}
/**
* 測試類
* */
class hello{
public static void main(String[] args) {
Info info=new Info();
Producer pro=new Producer(info);
Consumer con=new Consumer(info);
new Thread(pro).start();
new Thread(con).start();
}
}
【運行結(jié)果】:
Rollen<---->100
chunGe<---->20
chunGe<---->100
Rollen<---->100
chunGe<---->20
Rollen<---->100
Rollen<---->100
Rollen<---->100
chunGe<---->20
chunGe<---->20
chunGe<---->20
Rollen<---->100
chunGe<---->20
Rollen<---->100
chunGe<---->20
Rollen<---->100
chunGe<---->20
Rollen<---->100
chunGe<---->20
Rollen<---->100
chunGe<---->20
Rollen<---->100
chunGe<---->20
Rollen<---->100
chunGe<---->20
大家可以從結(jié)果中看到,名字和年齡并沒有對于。
那么如何解決呢?
1)加入同步
2)加入等待和喚醒
先來看看加入同步會是如何。
class Info {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public synchronized void set(String name, int age){
this.name=name;
try{
Thread.sleep(100);
}catch (Exception e) {
e.printStackTrace();
}
this.age=age;
}
public synchronized void get(){
try{
Thread.sleep(100);
}catch (Exception e) {
e.printStackTrace();
}
System.out.println(this.getName()+"<===>"+this.getAge());
}
private String name = "Rollen";
private int age = 20;
}
/**
* 生產(chǎn)者
* */
class Producer implements Runnable {
private Info info = null;
Producer(Info info) {
this.info = info;
}
public void run() {
boolean flag = false;
for (int i = 0; i < 25; ++i) {
if (flag) {
this.info.set("Rollen", 20);
flag = false;
} else {
this.info.set("ChunGe", 100);
flag = true;
}
}
}
}
/**
* 消費者類
* */
class Consumer implements Runnable {
private Info info = null;
public Consumer(Info info) {
this.info = info;
}
public void run() {
for (int i = 0; i < 25; ++i) {
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
this.info.get();
}
}
}
/**
* 測試類
* */
class hello {
public static void main(String[] args) {
Info info = new Info();
Producer pro = new Producer(info);
Consumer con = new Consumer(info);
new Thread(pro).start();
new Thread(con).start();
}
}
【運行結(jié)果】:
Rollen<===>20
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
Rollen<===>20
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
ChunGe<===>100
從運行結(jié)果來看,錯亂的問題解決了,現(xiàn)在是 Rollen 對應(yīng)20,ChunGe 對于100,但是還是出現(xiàn)了重復(fù)讀取的問題,也肯定有重復(fù)覆蓋的問題。如果想解決這個問題,就需要使用 Object 類幫忙了,我們可以使用其中的等待和喚醒操作。
要完成上面的功能,我們只需要修改 Info 類饑渴,在其中加上標(biāo)志位,并且通過判斷標(biāo)志位完成等待和喚醒的操作,代碼如下:
class Info {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public synchronized void set(String name, int age){
if(!flag){
try{
super.wait();
}catch (Exception e) {
e.printStackTrace();
}
}
this.name=name;
try{
Thread.sleep(100);
}catch (Exception e) {
e.printStackTrace();
}
this.age=age;
flag=false;
super.notify();
}
public synchronized void get(){
if(flag){
try{
super.wait();
}catch (Exception e) {
e.printStackTrace();
}
}
try{
Thread.sleep(100);
}catch (Exception e) {
e.printStackTrace();
}
System.out.println(this.getName()+"<===>"+this.getAge());
flag=true;
super.notify();
}
private String name = "Rollen";
private int age = 20;
private boolean flag=false;
}
/**
* 生產(chǎn)者
* */
class Producer implements Runnable {
private Info info = null;
Producer(Info info) {
this.info = info;
}
public void run() {
boolean flag = false;
for (int i = 0; i < 25; ++i) {
if (flag) {
this.info.set("Rollen", 20);
flag = false;
} else {
this.info.set("ChunGe", 100);
flag = true;
}
}
}
}
/**
* 消費者類
* */
class Consumer implements Runnable {
private Info info = null;
public Consumer(Info info) {
this.info = info;
}
public void run() {
for (int i = 0; i < 25; ++i) {
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
this.info.get();
}
}
}
/**
* 測試類
* */
class hello {
public static void main(String[] args) {
Info info = new Info();
Producer pro = new Producer(info);
Consumer con = new Consumer(info);
new Thread(pro).start();
new Thread(con).start();
}
}
【程序運行結(jié)果】: Rollen<===>20 ChunGe<===>100 Rollen<===>20 ChunGe<===>100 Rollen<===>20 ChunGe<===>100 Rollen<===>20 ChunGe<===>100 Rollen<===>20 ChunGe<===>100 Rollen<===>20 ChunGe<===>100 Rollen<===>20 ChunGe<===>100 Rollen<===>20 ChunGe<===>100 Rollen<===>20 ChunGe<===>100 Rollen<===>20 ChunGe<===>100 Rollen<===>20 ChunGe<===>100 Rollen<===>20 ChunGe<===>100 Rollen<===>20 先在看結(jié)果就可以知道,之前的問題完全解決。 《完》
PS(寫在后面):
本人深知學(xué)的太差,所以希望大家能多多指點。另外,關(guān)于多線程其實有很多的知識,由于目前我也就知道的不太多,寫了一些常用的。雖然在操作系統(tǒng)這門課上學(xué)了很多的線程和進程,比如銀行家算法等等的,以后有時間在補充,大家有什么好資料可以留個言,大家一起分享一下,謝謝了