不同線程間進行通信通常有兩種簡單方法
方法一 通過訪問共享變量的方式(注
方法二 通過管道流
其中方法一有兩種實現方法
方法一a)通過內部類實現線程的共享變量
代碼如下
Java代碼
/**
* 通過內部類實現線程的共享變量
*
*/
public class Innersharethread {
public static void main(String[] args) {
Mythread mythread = new Mythread()
mythread
mythread
mythread
mythread
}
}
class Mythread {
int index =
private class InnerThread extends Thread {
public synchronized void run() {
while (true) {
System
+
}
}
}
public Thread getThread() {
return new InnerThread()
}
}
/**
* 通過內部類實現線程的共享變量
*
*/
public class Innersharethread {
public static void main(String[] args) {
Mythread mythread = new Mythread()
mythread
mythread
mythread
mythread
}
}
class Mythread {
int index =
private class InnerThread extends Thread {
public synchronized void run() {
while (true) {
System
+
}
}
}
public Thread getThread() {
return new InnerThread()
}
}
方法二b)通過實現Runnable接口實現線程的共享變量
代碼如下
Java代碼
/**
* 通過實現Runnable接口實現線程的共享變量
* @author Administrator
*
*/
public class Interfacaesharethread {
public static void main(String[] args) {
Mythread mythread = new Mythread()
new Thread(mythread)
new Thread(mythread)
new Thread(mythread)
new Thread(mythread)
}
}
/* 實現Runnable接口 */
class Mythread implements Runnable {
int index =
public synchronized void run() {
while (true)
System
+
}
}
/**
* 通過實現Runnable接口實現線程的共享變量
* @author Administrator
*
*/
public class Interfacaesharethread {
public static void main(String[] args) {
Mythread mythread = new Mythread()
new Thread(mythread)
new Thread(mythread)
new Thread(mythread)
new Thread(mythread)
}
}
/* 實現Runnable接口 */
class Mythread implements Runnable {
int index =
public synchronized void run() {
while (true)
System
+
}
}
方法二
代碼如下
Java代碼
import java
import java
import java
public class CommunicateWhitPiping {
public static void main(String[] args) {
/**
* 創建管道輸出流
*/
PipedOutputStream pos = new PipedOutputStream()
/**
* 創建管道輸入流
*/
PipedInputStream pis = new PipedInputStream()
try {
/**
* 將管道輸入流與輸出流連接
* 此過程也可通過重載的構造函數來實現
*/
nnect(pis)
} catch (IOException e) {
e
}
/**
* 創建生產者線程
*/
Producer p = new Producer(pos)
/**
* 創建消費者線程
*/
Consumer c = new Consumer(pis)
/**
* 啟動線程
*/
p
c
}
}
/**
* 生產者線程(與一個管道輸入流相關聯)
*
*/
class Producer extends Thread {
private PipedOutputStream pos;
public Producer(PipedOutputStream pos) {
this
}
public void run() {
int i =
try {
pos
} catch (IOException e) {
e
}
}
}
/**
* 消費者線程(與一個管道輸入流相關聯)
*
*/
class Consumer extends Thread {
private PipedInputStream pis;
public Consumer(PipedInputStream pis)
{
this
}
public void run() {
try {
System
} catch (IOException e) {
e
}
}
}
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27464.html