多线程求解
package com.hzxxb.thread;
public class ThreadTest {
public static void main(String[] args) {
Num n = new Num();
//P p = new P(n);
//C c = new C(n);
Thread p = new P(n);
Thread c = new C(n);
p.setPriority(Thread.MAX_PRIORITY);
p.start();
c.start();
}
}
class P extends Thread {
Num n = null;
public P(Num n) {
this.n = n;
}
public void run() {
for (int i = 0; i < 10; i++) {
/**
* 差异
*/
n.setI(i);
System.out.println("生产者放入:" + i);
}
}
}
class C extends Thread {
Num n = null;
public C(Num n) {
this.n = n;
}
public void run() {
while (true) {
System.out.println("消费者获取:" + n.getI());
}
}
}
class Num {
private int i;
private boolean isFull = false;
public synchronized int getI() {
if (!isFull) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isFull = false;
notify();
return i;
}
public synchronized void setI(int i) {
if (!isFull) {
this.i = i;
isFull = true;
notify();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
结果:
消费者获取:0
生产者放入:0
生产者放入:1
消费者获取:1
消费者获取:2
生产者放入:2
消费者获取:3
生产者放入:3
生产者放入:4
消费者获取:4
消费者获取:5
生产者放入:5
生产者放入:6
消费者获取:6
生产者放入:7
消费者获取:7
生产者放入:8
消费者获取:8
消费者获取:9
生产者放入:9
-------------------
以下修改class P{}
class P extends Thread {
Num n = null;
public P(Num n) {
this.n = n;
}
public void run() {
for (int i = 0; i < 10; i++) {
/**
* 差异
*/
System.out.println("生产者放入:" + i);
n.setI(i);
}
}
}
结果为:
生产者放入:0
消费者获取:0
生产者放入:1
消费者获取:1
生产者放入:2
消费者获取:2
生产者放入:3
消费者获取:3
生产者放入:4
生产者放入:5
消费者获取:4
生产者放入:6
消费者获取:5
消费者获取:6
生产者放入:7
消费者获取:7
生产者放入:8
消费者获取:8
生产者放入:9
消费者获取:9
这是为何?