码迷,mamicode.com
首页 > 编程语言 > 详细

多线程核心点

时间:2017-01-09 18:29:09      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:his   write   ati   print   ring   protected   private   sync   form   

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

多线程核心点

标签:his   write   ati   print   ring   protected   private   sync   form   

原文地址:http://www.cnblogs.com/JosephWang/p/6265700.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!