今天学习了java的多线程问题,所以通过多线程的方法实现了多线程的消费者生产者问题。其中线程的start方面说明线程可以使用cpu的资源了,但是并不代表线程马上就会执行run方法
package com.jk.test;
public class Test {
public static void main(String[] args) {
//创建存储室对象并分配内存
Storage st = new Storage();
//消费者和生产者的对象创建和内存分配
Consumer s = new Consumer(st);
Producer p = new Producer(st);
//启动消费者和生产者线程
s.start();
p.start();
}
}
package com.jk.test;
public class Storage {
int number = 0;
int size = 10;
//synchronized 表示进入当前方法后,其它线程不能进入
public synchronized void product() {
if (number == size) {
try {
//线程休眠
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
number++;
//因为至少有一个食物了,所以唤醒其它线程
notifyAll();
}
public synchronized void consume() {
if (number == 0) {
try {
//线程休眠
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
number--;<pre name="code" class="java">package com.jk.test;
public class Producer extends Thread {
Storage st = null;
public Producer(Storage st) {
super();
this.st = st;
}
@Override
public void run() {
// TODO Auto-generated method stub
//super.run();
for (int i = 0; i < 100; i++) {
//调用储存室里面的生产方法
st.product();
System.out.println("生产者: " +st.number);
}
}
}
package com.jk.test;
public class Producer extends Thread {
Storage st = null;
public Producer(Storage st) {
super();
this.st = st;
}
@Override
public void run() {
// TODO Auto-generated method stub
//super.run();
for (int i = 0; i < 100; i++) {
//调用储存室里面的生产方法
st.product();<pre name="code" class="java">package com.jk.test;
public class Producer extends Thread {
Storage st = null;
public Producer(Storage st) {
super();
this.st = st;
}
@Override
public void run() {
// TODO Auto-generated method stub
//super.run();
for (int i = 0; i < 100; i++) {
//调用储存室里面的生产方法
st.product();
System.out.println("生产者: " +st.number);
}
}
}
System.out.println("生产者: " +st.number);}}}
//因为最多有食物总数减1,所以唤醒所有线程notifyAll();}}
<pre name="code" class="html">package com.jk.test;
public class Producer extends Thread {
Storage st = null;
public Producer(Storage st) {
super();
this.st = st;
}
@Override
public void run() {
// TODO Auto-generated method stub
//super.run();
for (int i = 0; i < 100; i++) {
//调用储存室里面的生产方法
st.product();
System.out.println("生产者: " +st.number);
}
}
}
package com.jk.test;
import java.util.concurrent.ThreadFactory;
public class Consumer extends Thread {
public Storage st = null;
public Consumer(Storage st) {
super();
this.st = st;
}
public void run() {
// TODO Auto-generated method stub
//super.run();
for (int i = 0; i < 100; i++) {
//调用储存室里面的consume方法
st.consume();
System.out.println("消费者:" +st.number);
}
}
}