死锁Demo(一人拿到一个资源,相互等待对方释放资源,解决方法别在一个同步代码块中再写一个同步代码块应该使它们同级):
package com.kuang;
public class DeathLock {
public static void main(String []args) {
MakeUp t1=new MakeUp(1,"小红帽");
MakeUp t2=new MakeUp(2,"白雪公主");
t1.start();
t2.start();
}
}
class Mirror{ //镜子
}
class Lipstick{ //口红
}
class MakeUp extends Thread{
// public Mirror mirror =new Mirror();
// public Lipstick lisptick=new Lipstick();
private String mirror="mirror";
private String lisptick="lisptick";
private int choose;
String name;
MakeUp(int choose,String name){
this.choose =choose;
this.name=name;
}
@Override
public void run() {
try {
makeUp();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void makeUp() throws InterruptedException {
if(choose==1) {
synchronized (this.lisptick) {
System.out.println(this.name+"获得了口红");
Thread.sleep(1000);
synchronized (this.mirror) {
System.out.println(this.name+"获得了镜子");
}
}
}else if(choose==2){
synchronized (this.mirror) {
System.out.println(this.name+"获得了镜子");
Thread.sleep(1000);
synchronized (this.lisptick) {
System.out.println(this.name+"获得了口红");
}
}
}
}
}
资源同级的解决方法如下(this.lisptick都是外层的同步代码块锁,this.mirror都是内层的同步代码块锁):
private void makeUp() throws InterruptedException {
if(choose==1) {
synchronized (this.lisptick) {
System.out.println(this.name+"获得了口红");
Thread.sleep(1000);
synchronized (this.mirror) {
System.out.println(this.name+"获得了镜子");
}
}
}else if(choose==2){
synchronized (this.lisptick) {
System.out.println(this.name+"获得了镜子");
Thread.sleep(1000);
synchronized (this.mirror) {
System.out.println(this.name+"获得了口红");
}
}
}
线程通信Demo(生产者做一只鸡,消费者吃一只鸡):
package com.kuang;
public class ThreadCommunication {
public static void main(String[] args) {
Container container = new Container();
Producer producer = new Producer(container);
Customer customer = new Customer(container);
producer.start();
customer.start();
}
}
class Producer extends Thread {
private Container container;
public Producer(Container container) {
this.container = container;
}
@Override
public void run() {
for(int i=0;i<100;i++) {
container.makeChicken();
}
}
}
class Customer extends Thread {
private Container container;
public Customer(Container container) {
this.container = container;
}
@Override
public void run() {
for(int i=0;i<100;i++) {
container.getChicken();
}
}
}
class Container {
int count = 0; // 炸鸡的数量
boolean flag = true; // 为true需要做鸡
public synchronized void makeChicken() {
if(flag==false) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
count++;
System.out.println("生产者做了" + count + " 只鸡");
flag=false;
notifyAll();
}
public synchronized void getChicken() {
if(flag==true) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("消费者吃了" + count + " 只鸡-----");
flag=true;
count--;
notifyAll();
}
}