一、Java中线程分为两类:
用户线程:平时用到的普通线程均是用户线程
守护线程(后台线程):Java垃圾回收就是一个典型的守护线程。
如果JVM中所有的线程都是守护线程,那么JVM就会退出,进而守护线程也会退出。
如果JVM中还存在用户线程,那么JVM就会一直存活,不会退出。
主线程退出后,守护线程依然在运行!
由此得到只要任何非守护线程还在运行,守护线程就不会终止。
一般守护线程是一个死循环,所有的用户线程只要结束,守护线程就结束。
设置守护线程:thread.setdaemon(true)
可以用守护线程实现定时器
作用:间隔特定的时间,执行特定的程序。同时Java的类库中写好了定时器 java.util.Timer
二、Object类中的wait()和notify()方法
在这之前,先了解锁池和等待池的概念:
锁池和等待池
锁池:
假设线程A已经拥有了某个对象(不是类)的锁,而其它线程B,C想要调用这个对象的某个synchronized方法(或者块)之前必须获得该对象锁的拥有权,而恰巧该对象的锁目前正被A所占有,此时B,C线程就会被阻塞,进入一个地方去等待锁的释放,这个地方便是该对象的锁池。
等待池
假设线程A调用了某个对象的wait方法,线程A就会释放该对象的锁,同时线程A就进入到了该对象的等待池中,进入等待池中的线程不会去竞争该对象的锁
wait() 让当前在该对象上活动的线程进入等待状态,无限期的等待,直到被唤醒。wait方法的调用,会让正在该对象的当前线程进入等待状态并释放锁。
notify()方法:会随机选一个处于等待池的线程进入锁池去竞争获取锁的机会。
notifyAll:会让所有处于等待池的线程全部进入锁池去竞争获取锁的机会。
Wait()和notify()方法只能从synchronized方法或块中调用,需要在其他线程正在等待的对象上调用notify方法。
生产者与消费者的一个简单案例
生产者:
public class Producer implements Runnable {private Storehouse storehouse;public Producer(Storehouse storehouse) {this.storehouse = storehouse;}@Overridepublic void run() {for (int i = 0; i < 10; i++) {storehouse.in();}}}
消费者:
public class Consumer implements Runnable{private Storehouse storehouse;public Consumer(Storehouse storehouse) {this.storehouse = storehouse;}@Overridepublic void run() {for (int i = 0; i < 10; i++) {storehouse.out();}}}
仓库:
public class Storehouse {private List list;public List getList() {return list;}public void setList(List list) {this.list = list;}public Storehouse(List list) {this.list = list;}//生产的方法public synchronized void in(){if(this.getList().size() > 0){try {wait();} catch (InterruptedException e) {e.printStackTrace();}}//生产this.getList().add(new Object());System.out.println(Thread.currentThread().getName()+"生产了一个产品,对象为"+this.getList().get(0));try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}notifyAll();}//消费的方法public synchronized void out(){if(this.getList().size() == 0){try {//仓库如果是空的,消费者进入等待池等待wait();} catch (InterruptedException e) {e.printStackTrace();}}//正常消费Object remove = this.getList().remove(0);System.out.println(Thread.currentThread().getName()+"成功消费,消费的商品为"+remove);try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}notifyAll();}}
测试类:
public class Test {public static void main(String[] args) {//共享对象Storehouse storehouse = new Storehouse(new ArrayList());//生产者线程对象Thread t1 = new Thread(new Producer(storehouse));t1.setName("t1");//消费者线程对象Thread t2 = new Thread(new Consumer(storehouse));t2.setName("t2");t1.start();t2.start();}}
