多线程-同步与死锁
程序员文章站
2022-05-22 11:13:53
...
进程:是程序的执行过程(是一个动态的),进程中持有资源(共享内存,共享文件)和线程
线程:是系统中最小的执行单元,同一进程中有多个线程,线程共享进程的资源
线程的5种状态:
同步什么时间用:资源共享时需要进行同步操作
同步的缺点:程序中过多的同步会产生死锁
经典案例:生产者消费者问题:在synchronized里面加标志位boolean flag 判断是否可以生产(还是取走),可以解决。
package com.guojinlong.xiancheng;
class Info{
private String name="初始化";
private String content="初始化讲师";
private Boolean flag=true;
public synchronized void set(String name,String content) {
if(!flag) {
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name=name;
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.content=content;
flag=false;
super.notifyAll();
}
public synchronized void get() {
if(flag) {
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.name+"==="+this.content);
flag=true;
super.notifyAll();
}
}
class Producer implements Runnable{
private Info info=null;
public Producer(Info info) {
this.info=info;
}
@Override
public void run() {
boolean flag=false;
for(int i=0;i<50;i++){
if(flag) {
this.info.set("小明", "java讲师");
flag=false;
}else {
this.info.set("小兰", "DBA讲师");
flag=true;
}
}
}
}
class Consumer implements Runnable{
private Info info=null;
public Consumer(Info info) {
this.info=info;
}
@Override
public void run() {
for(int i=0;i<50;i++) {
this.info.get();
}
}
}
public class ThreadCaseDemo1 {
public static void main(String [] args) {
Info info = new Info();
Producer producer = new Producer(info);
Consumer consumer = new Consumer(info);
new Thread(producer).start();
new Thread(consumer).start();
}
}
未完...(如有任何问题,欢迎指出)