该系列文章只是记录本人回顾java多线程编程时候记录的笔记。文中所用语言并非严谨的专业术语(太严谨的术语其实本人也不会……)。难免有理解偏差的地方,欢迎指正。 另外,大神请绕路。不喜勿喷。 毕竟好记性不如烂笔头嘛,而且许多东西只要不是你经常用的最终都会一丢丢一丢丢地给忘记。
先看看下面这张来自百度的java线程状态图:
新建状态(New)用new语句创建的线程处于新建状态,只是为他分配了内存,并没有开始运行。
就绪状态(Runnable)调用start()方法,线程就进入就绪状态。 然而也仅仅是处于可运行状态,到底能不能立即运行还要看操作系统的调度。
运行状态(Running)此时是真正的处于运行状态。是由可运行状态到运行状态。
阻塞状态(Blocked)线程由于某些原因放弃CPU的占有权。当线程处于阻塞状态时。直到下次该线程处于可运行状态时才有可能再次进入运行状态。
可能的阻塞原因:
- 调用了wait方法,进入了等待池。 - 等待某些资源可用。 - I/O等待、调用了sleep方法、其他线程的join方法等。 死亡状态(Dead)线程执行结束。注意一个已经死亡的线程是没办法“复活”的。只能重新new一个。
大多数资料都显示,java中的线程优先级并不会生效,往往会被操作系统直接忽略。 所以,此处对这部分内容直接略过。
daemon线程又称为后台线程或精灵线程。
可以通过setDaemon(boolean isDeamon)将一个线程设置为后台线程。比如java的垃圾回收线程。
注意:
当JVM中不存在非daemon线程的时候,JVM就会退出。将一个线程设置为Daemon线程,必须在其启动之前进行设置。java线程的中断表示的是:某个线程是否被其他线程中断过。相当于一个boolean类型的标识位。 此处的中断过类似于你正在写代码,突然有人找你说话,此处可以理解为被中断了。
isInterrupted():是否被中断(如果线程已经结束了,也会返回false)Thread.interrupted():复位中断标志线程被中断后抛出java.lang.InterruptedException异常,但是在异常被抛出之前,JVM会先将中断标识位复位。也就是说,在抛出java.lang.InterruptedException异常之后并且在下次中断之前调用isInterrupted()方法会返回false。
这三个API都是deprecated的。已经被废弃。此处提出来只是为了知识点的完整性。
suspend():暂停(睡眠)线程resume():恢复线程stop():终止线程在《java并发编程的艺术》一书中,作者举了个很形象的例子来说明这三个方法的作用:CD机播放音乐时暂停(suspend)、恢复(resume)和停止(stop)的操作。同时,作者也说明了这三个人性化的方法之所以过时是因为:
suspend方法会一致占有着拥有的资源进入睡眠状态stop方法在终止的线程的时候对资源的释放没有保证任何对象都有自己的监视器。当某个对象被同步方法或者同步块调用时,执行方法的线程必须先获得其监视器。 没有获取到监视器的线程将被阻塞在方法的入口处进入阻塞(blocked)状态。
所以,任何对象都可以被当做锁来使用。
一般而言,线程通信至少有两种方式:消息传递和共享内存。
在java里一般是共享内存实现的线程通信。当然也有第三方的消息传递模型的线程通信。 下文所说的线程通信指的是共享内存模型。
和线程通信相关的方法
methodDESCnotify()通知一个在对象上等待的线程,使其从wait()方法返回,返回的前提是该线程获取到了对象的锁notifyAll()通知所有等待在该对象上的线程wait()调用wait方法的线程将释放锁(如果已经持有锁的话)并进入waiting状态。只有等待其他线程的通知或被中断才会返回。wait(long t)和wait方法的不同是:等待t毫秒还是没有被唤醒的话会“超时返回”wait(long,int)对超时时间控制更加细致的wait(long)版本join()线程T调用tx.join()的意思是:T等待tx线程结束后才从tx.join()返回,接着执行T自己的后续代码几个注意点
调用wait、notify、notifyAll时必须先获得锁调用wait方法后,线程有running状态–>waitting状态,并将当前线程至于对象的等待池中。调用notify或者notifyAll方法后waiting状态的线程能够返回的前提是:调用notifyAll或notify方法的线程先释放锁,并且该线程获得了锁。notify调用后,会将等待池(等待队列)中的一个线程移动到同步队列中。被移动的线程状态:waiting–>blocked。notifyAll方法调用后,会将等待池中所有的线程移动至同步队列中。被移动的线程状态:waiting–>blocked。join()的一个有趣的例子
* 注意:该示例来自《java并发编程的艺术》一书*
import java.util.concurrent.TimeUnit; public class Join { public static void main(String[] args) throws Exception { Thread previous = Thread.currentThread(); for (int i = 0; i < 10; i++) { // 每个线程拥有前一个线程的引用,需要等待前一个线程终止,才能从等待中返回 Thread thread = new Thread(new Runner(previous), String.valueOf(i)); thread.start(); previous = thread; } TimeUnit.SECONDS.sleep(5); System.out.println(Thread.currentThread().getName() + " terminate."); } static class Runner implements Runnable { private Thread previous; public Runner(Thread thread) { this.previous = thread; } public void run() { try { previous.join(); } catch (InterruptedException e) { } System.out.println(Thread.currentThread().getName() + " terminate."); } } }以上示例的结果其实就是所有线程依次串行执行。
此处是本人改写的一个生产者和消费者的案例。
生产者不断生成,消费者不断消费。
public class ProducerConsumer { public static void main(String[] args) { Container container = new Container(5); for (int i = 0; i < 10; i++) { new Thread(new Producer(container), "P-" + i).start(); new Thread(new Consumer(container), "C-" + i).start(); } } public static class Product { private String name; public Product(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "[name=" + name + "]"; } } public static class Container { private int nextIndex = 0; Product[] products = null; public Container(int size) { this.products = new Product[size > 0 ? size : 5]; } public void push(Product product) { synchronized (products) { while (this.nextIndex >= this.products.length) { try { // 访问products的线程先wait this.products.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // 叫醒在products等待池上等待的线程 this.products.notifyAll(); this.products[nextIndex++] = product; } } public Product pop() { synchronized (products) { while (this.nextIndex <= 0) { try { this.products.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // 叫醒在products等待池上等待的线程 this.products.notifyAll(); return this.products[--nextIndex]; } } } public static class Producer implements Runnable { private Container container; public Producer(Container container) { super(); this.container = container; } @Override public void run() { for (int i = 0; i < Integer.MAX_VALUE; i++) { Product p = new Product(Thread.currentThread().getName() + "_" + i); this.container.push(p); System.out.println("生产者[" + Thread.currentThread().getName() + "]生产>>>>>>:" + p); try { Thread.sleep((long) (Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static class Consumer implements Runnable { private Container container; public Consumer(Container container) { super(); this.container = container; } @Override public void run() { for (int i = 0; i < Integer.MAX_VALUE; i++) { Product product = this.container.pop(); System.out.println("消费者[" + Thread.currentThread().getName() + "]消费<<<<<<:" + product); try { Thread.sleep((long) (Math.random() * 2000)); } catch (InterruptedException e) { e.printStackTrace(); } } } } }