package com.xhj.thread;
/**
* 线程之间的通信 Thread.yeild()暂停当前线程,执行其他线程
*
* @author XIEHEJUN
*
*/
public class CommunicationThread {
/**
* 发送线程类
*
* @author XIEHEJUN
*
*/
private class SendThread implements Runnable {
private String[] products = { "java宝典", "C#宝典", "C宝典", "C++宝典",
"Pyhtion宝典" };
private volatile String productName;
private volatile boolean sendState;
public String getProductName() {
return productName;
}
public void setSendState(boolean sendState) {
this.sendState = sendState;
}
public boolean isSendState() {
return sendState;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
while (sendState) {
Thread.yield();
}
productName = products[i];
System.out.println("发送:" + productName);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendState = true;
}
}
}
/**
* 接受线程类
*
* @author XIEHEJUN
*
*/
private class ReceiveThrend implements Runnable {
private SendThread send;
public ReceiveThrend(SendThread send) {
this.send = send;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
while (!send.isSendState()) {
Thread.yield();
}
System.out.println("接收:" + send.getProductName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
send.setSendState(false);
}
}
}
/**
* 调用线程
*/
public void useThread() {
SendThread send = new SendThread();
ReceiveThrend receive = new ReceiveThrend(send);
System.out.println("线程1");
Thread thread1 = new Thread(send);
thread1.start();
System.out.println("线程2");
Thread thread2 = new Thread(receive);
thread2.start();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CommunicationThread communicationThread = new CommunicationThread();
communicationThread.useThread();
}
}