Java執行緒間通訊,最常用的方式便是共享變數方式,多個執行緒共享一個靜態變數就可以實現線上程間通訊,但是這需要注意的就是執行緒同步問題。
一、沒考慮執行緒同步:
package com.wyf; public class threadConnetcion {
public static void main(String[] args) { Q q=new Q();
//建立生產者執行緒
Producer p = new Producer(q); //建立消費者執行緒
Consumer c = new Consumer(q);
/**
* 啟動執行緒
*/
p.start();
c.start();
} } //生產者執行緒
class Producer extends Thread {
Q q;
public Producer(Q q) {
this.q = q;
} public void run() {
try {
int i=0;
while(true)
{
this.sleep(3000);
q.put(i++);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} //消費者執行緒
class Consumer extends Thread {
Q q;
public Consumer(Q q) {
this.q = q;
} public void run() {
try {
while(true)
{
this.sleep(3000);
q.get();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} class Q
{
int n; synchronized int get()
{
System.out.println("Get:"+n);
return n;
} synchronized void put(int n)
{
this.n=n;
System.out.println("Put:"+n);
}
}
輸出如下:
Put:0
Get:0
Get:0
Put:1
Put:2
Get:2
Get:2
Put:3
Get:3
Put:4
Put:5
Get:5
Put:6
Get:6
Get:6
Put:7
Put:8
Get:8
可以看到執行緒之間的通訊是雜亂的;
二、使用wait和notify進行執行緒同步:
package com.wyf; public class threadConnetcion {
public static void main(String[] args) { Q q=new Q();
//建立生產者執行緒
Producer p = new Producer(q); //建立消費者執行緒
Consumer c = new Consumer(q);
/**
* 啟動執行緒
*/
p.start();
c.start();
} } //生產者執行緒
class Producer extends Thread {
Q q;
public Producer(Q q) {
this.q = q;
} public void run() {
try {
int i=0;
while(true)
{
this.sleep(3000);
q.put(i++);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} //消費者執行緒
class Consumer extends Thread {
Q q;
public Consumer(Q q) {
this.q = q;
} public void run() {
try {
while(true)
{
this.sleep(3000);
q.get();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} class Q
{
int n;
boolean valueSet=false; synchronized int get()
{
while(!valueSet)
{
try
{
wait();
}
catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("Get:"+n);
valueSet=false;
notify();
return n;
} synchronized void put(int n)
{
while(valueSet)
{
try
{
wait();
}
catch (Exception e) {
e.printStackTrace();
}
}
this.n=n;
System.out.println("Put:"+n);
valueSet=true;
notify();
}
}
輸出如下:
Put:0
Get:0
Put:1
Get:1
Put:2
Get:2