一、生产消费者
import java.util.LinkedList;
import java.util.List;
public class ProducerAndConsumer {
private static class Goods{
public Goods(){
this(null);
}
public Goods(String name) {
this.name = name;
}
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
private static class Producer implements Runnable {
private List<Goods> list;
private int count = 0;
Producer(List<Goods> list) {
this.list = list;
}
@Override
public void run() {
while (true) {
synchronized(list) {
//队列中不为空,则释放锁
while (!list.isEmpty()) {
try {
list.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//生产产品
Goods goods = new Goods();
goods.setName("" + count);
count = count == 0 ? 1 : 0;
list.add(goods);
System.out.println("生产了产品:" + goods.getName());
list.notify();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
private static class Consumer implements Runnable {
private List<Goods> list;
private Consumer(List<Goods> list) {
this.list = list;
}
@Override
public void run() {
while (true) {
synchronized(list) {
while (list.isEmpty()) {
try {
list.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
Goods goods = list.remove(0);
System.out.println("消费了产品:" + goods.getName());
list.notify();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
public static void main(String[] args) {
List<Goods> list = new LinkedList<>();
new Thread(new Producer(list)).start();
new Thread(new Consumer(list)).start();
}
}
二、死锁代码
public class DeadLock {
private static class DeadLockRunable implements Runnable {
private Object aLock = new Object();
private Object bLock = new Object();
private int count = 0;
@Override
public void run() {
while (true) {
if (count == 0) {
synchronized (aLock) {
System.out.println("获取了:aLock");
synchronized (bLock) {
System.out.println("获取了:bLock");
}
}
} else {
synchronized (bLock) {
System.out.println("获取了:bLock");
synchronized (aLock) {
System.out.println("获取了:aLock");
}
}
}
count = count == 0 ? 1 : 0;
}
}
}
public static void main(String[] args) {
DeadLockRunable deadLockRunable = new DeadLockRunable();
new Thread(deadLockRunable).start();
new Thread(deadLockRunable).start();
}
}
网友评论