首页 > 代码库 > 多线程核心点

多线程核心点

多线程编程核心:同步、线程通信
下面通过java演示多个生产-多个消费者来分析【同步】与【线程通信】
同步:生产者之间、消费者之间、生产与消费者之间
线程通信:生产向消费者发送通知:完成生产; 消费向生产发送通知:完成消费。

直接上代码

package javaapplication1;

public class JavaApplication1 {
//用于演示的主类
public static void main(String[] args) {
Container Student = new Container();
for (int i = 0; i < 7; i++) {
new Thread(new Produce(Student), String.format("生产%s", i)).start();
new Thread(new Consome(Student), String.format("消费%s", i)).start();
}
}
}

package javaapplication1;

//生产者
public class Produce implements Runnable {

private Container student;

public Produce(Container student) {
this.student = student;
}

public void run() {
for (int i = 0; i < 1; i++) {
synchronized (student.write) { //消费锁同步
synchronized (student.container) { //容器同步:生产-消费
if (this.student.value != 0) {
try {
this.student.container.wait();
} catch (InterruptedException ex) {
System.out.println(ex.getMessage());
}
}

this.student.allValue += 1;
this.student.value = http://www.mamicode.com/this.student.allValue;
System.out.println(String.format("%s, 生产了%s", Thread.currentThread().getName(), this.student.value));
this.student.container.notify();
}
}
}
}
}

package javaapplication1;

//消费者
public class Consome implements Runnable {

private Container student;

public Consome(Container student) {
this.student = student;
}

public void run() {
for (int i = 0; i < 1; i++) {
synchronized (student.read) { //消费锁同步
synchronized (student.container) { //容器同步:生产-消费
if (this.student.value =http://www.mamicode.com/= 0) {
try {
this.student.container.wait();
} catch (InterruptedException ex) {
System.out.println(ex.getMessage());
}
}

System.out.println(String.format("%s, 消费了%s", Thread.currentThread().getName(), student.allValue));
this.student.value = http://www.mamicode.com/0;
this.student.container.notify();
}
}
}
}
}


package javaapplication1;

//生产-消费的容器
public class Container {

protected int value;
protected int allValue;
protected String write;
protected String read;
protected String container;

public Container() {
this.write = "write";
this.read = "read";
this.container = "container";
}
}

多线程核心点