JVM启动时就启动了多个线程,至少有俩个线程可以分析出来
1、执行main函数的线程
该线程的任务代码都定义在main函数中
2、负责垃圾回收的线程
线程安全问题的产生
1、多个线程在操作共享的数据
2、操作共享数据的线程代码有多条
当一个线程在执行操作共享数据的代码过程中,其他线程参与了运算,就会导致安全问题
解决思路:
就是将多条操作的共享数据的线程代码封装起来,当有线程在执行这些代码的时候,其他线程时不可以参与运算的。
必须要当前线程把这些代码都执行完毕后,其他线程才可以参与运算。
同步
synchronized 同步,同步代码块可以解决线程安全问题
格式: synchronized(对象){需要被同步的代码;} //对象极为同步锁
同步好处:解决了线程安全的问题
同步弊端:相对降低了效率,因为同步外的线程都会判断同步锁
同步的前提:必须有多个线程并使用同一把锁
同步函数:public synchronized void hanshuname(){}
同步函数的使用的锁是this
同步函数与同步代码块区别:
同步函数的锁是固定的this,同步代码块的锁是任意的对象。建议使用同步代码块
静态同步函数使用的锁是该函数所属字节码文件对象,可以用getclass()获取,也可以用.class获取
死锁产生的原因:
两个锁A和B,线程A持有A,申请获得锁B,而B被另一个线程所持有,因为默认的锁申请都是阻塞的,所以产生死锁。
线程通讯:
多个线程在处理同一资源,但是任务却不同(同一个锁)
等待唤醒机制:1、wait(); 2、notify(); 3、notifyAll();
wair():让线程处于冻结状态,被wait的线程会被存储到线程池中
notify();唤醒线程池中的一个线程(任意)
notifyAll();唤醒线程池中的所有线程
这些方法都必修定义在同步中。因为这些方法是用于操作线程状态的方法,必须要明确到底操作的是哪个锁。
三个方法定义在object类中,因为这些方法是监视器的方法。监视器其实就是锁。锁可以是任意的对象,任意对象调用的方法一定在object中。
多生产者与多消费者例子:
package Test;
/*
* 生产者和消费者
*
* 多生产者和多消费者
*
* if判断标记,只有一次,会导致不该运行的线程运行了。出现了数据错误的情况。
* while判断标记,解决了线程获取执行权后,是否要运行。
*
* notify只能唤醒一个线程,如果本方唤醒了本方,没有意义。而且while判断标记+notify会导致死锁。
* notifyAll解决了,本方线程一定会唤醒对方线程
*/
class Resource {
private String name;
private int count = 1;
boolean flag = false;
public synchronized void set(String name) {
while (flag)
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.name = name + count;
count++;
System.out.println(Thread.currentThread().getName() + this.name);
flag = true;
notifyAll();
}
public synchronized void out() {
while (!flag)
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " ...消费者...." + this.name);
flag = false;
notifyAll();
}
}
class Producer implements Runnable {
private Resource r;
public Producer(Resource r) {
// TODO Auto-generated constructor stub
this.r = r;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
r.set("烤肉");
}
}
}
class Constmer implements Runnable {
private Resource r;
public Constmer(Resource r) {
// TODO Auto-generated constructor stub
this.r = r;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
r.out();
}
}
}
public class ProtucerConstmer {
public static void main(String[] args) {
// TODO Auto-generated method stub
Resource resource = new Resource();
Producer producer = new Producer(resource);
Constmer constmer = new Constmer(resource);
Thread t1 = new Thread(producer);
Thread t11 = new Thread(producer);
Thread t2 = new Thread(constmer);
Thread t22 = new Thread(constmer);
t1.start();
t11.start();
t2.start();
t22.start();
}
}