在java中要想實現多線程,有兩種手段,一種是繼續Thread類,另外一種是實現Runable接口。
繼續Thread類
對於直接繼承Thread的類來說,代碼大致框架是:
class 類名 extends Thread{
方法1;
方法2;
…
public void run(){
// other code…
}
屬性1;
屬性2;
…
}
先看一個簡單的例子:
//繼承Thread類,直接調用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;
}
【運行結果】:A運行 0
A運行 1
A運行 2
A運行 3
A運行 4
B運行 0
B運行 1
B運行 2
B運行 3
B運行 4
我們會發現這些都是順序執行的,說明我們的調用方法不對,應該調用的是start()方法。當我們把上面的主函數修改爲如下所示的時候:
public static void main(String[] args) {
hello h1=new hello("A");
hello h2=new hello("B");
h1.start();
h2.start();
}
然後運行程序,輸出的可能的結果如下:
A運行 0
B運行 0
B運行 1
B運行 2
B運行 3
B運行 4
A運行 1
A運行 2
A運行 3
A運行 4
因爲需要用到CPU的資源,所以每次的運行結果基本是都不一樣的,呵呵。
注意:雖然我們在這裏調用的是start()方法,但是實際上調用的還是run()方法的主體。
那麼:爲什麼我們不能直接調用run()方法呢?
我的理解是:線程的運行需要本地操作系統的支持。如果你查看start的源代碼的時候,會發現:
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();
注意我用紅色加粗的那一條語句,說明此處調用的是start0()。並且這個這個方法用了native關鍵字,次關鍵字表示調用本地操作系統的函數。因爲多線程的實現需要本地操作系統的支持。
但是start方法重複調用的話,會出現java.lang.IllegalThreadStateException異常。
實現Runable接口
大致框架是:class 類名 implements Runnable{
方法1;
方法2;
…
public void run(){
// other code…
}
屬性1;
屬性2;
…
}
來先看一個小例子吧:
//實現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;
}
【可能的運行結果】:線程A運行 0
線程B運行 0
線程B運行 1
線程B運行 2
線程B運行 3
線程B運行 4
線程A運行 1
線程A運行 2
線程A運行 3
線程A運行 4
關於選擇繼承Thread還是實現Runnable接口?其實Thread也是實現Runnable接口的:
class Thread implements Runnable {
//…
public void run() {
if (target != null) {
target.run();
}
}
}
其實Thread中的run方法調用的是Runnable接口的run方法。不知道大家發現沒有,Thread和Runnable都實現了run方法,這種操作模式其實就是代理模式。關於代理模式,我曾經寫過一個小例子呵呵,大家有興趣的話可以看一下:http://www.cnblogs.com/rollenholt/archive/2011/08/18/2144847.html
Thread和Runnable的區別:
如果一個類繼承Thread,則不適合資源共享。但是如果實現了Runable接口的話,則很容易的實現資源共享。
//繼承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;
}
【運行結果】:
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
大家可以想象,如果這個是一個買票系統的話,如果count表示的是車票的數量的話,說明並沒有實現資源的共享。我們換爲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();
}
}
【運行結果】:
count= 5
count= 4
count= 3
count= 2
count= 1
總結一下吧,實現Runnable接口比繼承Thread類所具有的優勢:
1)適合多個相同的程序代碼的線程去處理同一個資源
2)可以避免java中的單繼承的限制
3)增加程序的健壯性,代碼可以被多個線程共享,代碼和數據獨立。
所以,本人建議大家勁量實現接口。
//取得線程的名稱
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();
}
}
【運行結果】:A
A
A
B
B
B
Thread-0
Thread-0
Thread-0
說明如果我們沒有指定名字的話,系統自動提供名字。
提醒一下大家:main方法其實也是一個線程。在java中所以的線程都是同時啓動的,至於什麼時候,哪個先執行,完全看誰先得到CPU的資源。
在java中,每次程序運行至少啓動2個線程。一個是main線程,一個是垃圾收集線程。因爲每當使用java命令執行一個類的時候,實際上都會啓動一個JVM,每一個jVM實習在就是在操作系統中啓動了一個進程。
判斷線程是否啓動
//判斷線程是否啓動
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());
}
}
【運行結果】線程啓動之前---》false
線程啓動之後---》true
Thread-0
Thread-0
Thread-0
主線程也有可能在子線程結束之前結束。並且子線程不受影響,不會因爲主線程的結束而結束。
線程的強制執行:
//線程的強制執行
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(); //強制執行demo
}catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("main 線程執行-->"+i);
}
}
}
【運行的結果】:main 線程執行-->0
main 線程執行-->1
main 線程執行-->2
main 線程執行-->3
main 線程執行-->4
main 線程執行-->5
main 線程執行-->6
main 線程執行-->7
main 線程執行-->8
main 線程執行-->9
main 線程執行-->10
線程
線程
線程
main 線程執行-->11
main 線程執行-->12
main 線程執行-->13
...
線程的休眠:
//線程的休眠
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();
}
}
【運行結果】:(結果每隔2s輸出一個)線程0
線程1
線程2
線程的中斷:
//線程的中斷
class hello implements Runnable {
public void run() {
System.out.println("執行run方法");
try {
Thread.sleep(10000);
System.out.println("線程完成休眠");
} catch (Exception e) {
System.out.println("休眠被打斷");
return; //返回到程序的調用處
}
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後中斷線程
}
}
【運行結果】:
執行run方法
休眠被打斷
在java程序中,只要前臺有一個線程在運行,整個java程序進程不會小時,所以此時可以設置一個後臺線程,這樣即使java進程小時了,此後臺線程依然能夠繼續運行。
//後臺線程
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();
}
}
雖然有一個死循環,但是程序還是可以執行完的。因爲在死循環中的線程操作已經設置爲後臺運行了。線程的優先級:
//線程的優先級
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();
}
}
【運行結果】: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
但是請讀者不要誤以爲優先級越高就先執行。誰先執行還是取決於誰先去的CPU的資源。另外,主線程的優先級是5。
線程的禮讓:
在線程操作中,也可以使用yield()方法,將一個線程的操作暫時交給其他線程執行。
//線程的優先級
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運行0A運行1
A運行2
A運行3
線程的禮讓
A運行4
B運行0
B運行1
B運行2
B運行3
線程的禮讓
B運行4
同步和死鎖:
【問題引出】:比如說對於買票系統,有下面的代碼:
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;
}
【運行結果】:5
4
3
2
1
0
-1
這裏出現了-1,顯然這個是錯的。,應該票數不能爲負值。如果想解決這種問題,就需要使用同步。所謂同步就是在統一時間段中只有有一個線程運行,其他的線程必須等到這個線程結束之後才能繼續執行。
【使用線程同步解決問題】
採用同步的話,可以使用同步代碼塊和同步方法兩種來完成。
【同步代碼塊】:
語法格式:
synchronized(同步對象){
//需要同步的代碼
}
但是一般都把當前對象this作爲同步對象。比如對於上面的買票的問題,如下:
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;
}
【運行結果】:(每一秒輸出一個結果)
5
4
3
2
1
【同步方法】
也可以採用同步方法。語法格式:
synchronized 方法返回類型方法名(參數列表){
// 其他代碼
}
現在,我們採用同步方法解決上面的問題。
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;
}
【運行結果】(每秒輸出一個)5
4
3
2
1
提醒一下,當多個線程共享一個資源的時候需要進行同步,但是過多的同步可能導致死鎖。此處列舉經典的生產者和消費者問題。
【生產者和消費者問題】
先看一段有問題的代碼。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;
}
/**
* 生產者
* */
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();
}
}
【運行結果】: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
大家可以從結果中看到,名字和年齡並沒有對於。
那麼如何解決呢?
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;
}
/**
* 生產者
* */
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();
}
}
【運行結果】: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
從運行結果來看,錯亂的問題解決了,現在是Rollen 對應20,ChunGe對於100,但是還是出現了重複讀取的問題,也肯定有重複覆蓋的問題。如果想解決這個問題,就需要使用Object類幫忙了,我們可以使用其中的等待和喚醒操作。要完成上面的功能,我們只需要修改Info類飢渴,在其中加上標誌位,並且通過判斷標誌位完成等待和喚醒的操作,代碼如下:
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;
}
/**
* 生產者
* */
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();
}
}
【程序運行結果】: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
先在看結果就可以知道,之前的問題完全解決。
原文地址:http://www.cnblogs.com/rollenholt/archive/2011/08/28/2156357.html