上接第一章的线程状态
一个wait和notify的例子:
public class SynchronTest {
private int i=1;
public static void main(String[] args) {
Object lock = new Object();
SynchronTest s = new SynchronTest();
SycTest s1 = s.new SycTest(lock);
SycTest2 s2 = s.new SycTest2(lock);
Thread t1 = new Thread(s1,"Thread 1");
Thread t2 = new Thread(s2,"Thread 2");
t1.start();
t2.start();
}
class SycTest implements Runnable {
private Object lock;
public SycTest(Object lock){
this.lock = lock;
}
public synchronized void run() {
synchronized (lock){
while (i>0){
try {
System.out.println(Thread.currentThread().getName() + " start" );
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " end" );
}
}
}
}
class SycTest2 implements Runnable {
private Object lock;
public SycTest2(Object lock){
this.lock = lock;
}
public void run() {
synchronized(lock){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " start" );
i--;
lock.notify();
System.out.println(Thread.currentThread().getName() + " end" );
}
}
}
}
生产者消费者案例:
下面的例子是生产和消费两个线程并行,当生产到了20个的时候,就暂停,停止生产;当消费到0个的时候就暂停,停止消费;
public class ProducterConsumer {
public static void main(String[] args){
Object lock = new Object();
Pc pc = new Pc(lock);
ProducterThread pt = new ProducterThread(pc);
ConsumerThread ct = new ConsumerThread(pc);
new Thread(pt).start();
new Thread(ct).start();
}
}
class ProducterThread implements Runnable{
private Pc pc = null;
ProducterThread(Pc pc){
this.pc=pc;
}
@Override
public void run() {
pc.Producter();
}
}
class ConsumerThread implements Runnable{
private Pc pc = null;
ConsumerThread(Pc pc){
this.pc=pc;
}
@Override
public void run() {
pc.Consumer();
}
}
class Pc{
//初始化对象锁
private Object lock;
Pc(Object lock){
this.lock = lock;
}
private int j=0;
//生产者
public void Producter(){
while (true){
synchronized (lock){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(j==20){
System.out.println("已经满了");
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
j++;
System.out.println("生产了一个,现在有" + j + "个");
lock.notify();
}
}
}
}
//消费者
public void Consumer(){
while (true) {
synchronized (lock) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (j == 0) {
System.out.println("没有了,需要生产");
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
j--;
System.out.println("消耗了一个,还剩 "+j + "个");
lock.notify();
}
}
}
}
}
执行结果:
生产了一个,现在有1个
消耗了一个,还剩 0个
没有了,需要生产
生产了一个,现在有1个
生产了一个,现在有2个
生产了一个,现在有3个
生产了一个,现在有4个
消耗了一个,还剩 3个
消耗了一个,还剩 2个
消耗了一个,还剩 1个
消耗了一个,还剩 0个
没有了,需要生产
生产了一个,现在有1个
生产了一个,现在有2个