JAVA多线程之线程间通信的几种方式:
①同步 这里的同步是指多个线程通过synchronized关键字这种方式来实现线程间的通信
②while轮询方式
③wait/notify机制
④管道通信 使用java.io.PipedInputStream 和 java.io.PipedOutputStream进行通信(本文代码未涉及)
代码:
Queue类:
package queue;
public class Queue {
private int n;
private boolean flag = false;
public synchronized void setN(int n) {
if (flag == true) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("生产 " + n);
this.n = n;
flag = true;
notifyAll();
}
public synchronized int getN() {
if (flag == false) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("消费 " + n);
flag = false;
notifyAll();
return n;
}
}
Producer类:
package queue;
public class Producer implements Runnable {
private int i = 1;
Queue queueUse;
public Producer(Queue queue) {
this.queueUse = queue;
}
@Override
public void run() {
while (true) {
queueUse.setN(i++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Customer类:
package queue;
public class Customer implements Runnable {
Queue queueUse;
public Customer(Queue queue) {
this.queueUse = queue;
}
@Override
public void run() {
while (true) {
queueUse.getN();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
MainTest类:
package queue;
public class MainTest{
public static void main(String[] args) {
Queue queue=new Queue();
Producer producer = new Producer(queue);
Customer customer = new Customer(queue);
Thread threadP = new Thread(producer);
Thread threadC = new Thread(customer);
threadP.start();
threadC.start();
}
}