多线程核心点

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程核心点相关的知识,希望对你有一定的参考价值。

多线程编程核心:同步、线程通信
下面通过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 = 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 == 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 = 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";
}
}

以上是关于多线程核心点的主要内容,如果未能解决你的问题,请参考以下文章

多线程核心点

多线程核心技术 Chapter1

jvm-多线程

进程和线程

《Java多线程编程核心技术》多线程技能

多线程和CPU的关系