1 线程的创建

  • Java 从语言级别支持多线程
    • 如 Object 中的 wait()notify()
  • Java.lang 中的类 Thread** **
  • 线程体 —- run()

1.1 继承 Thread 类

  1. class MyThread extends Thread {
  2. public void run() {
  3. for (int i = 0; i < 100; ++i) {
  4. System.out.println(" " + i);
  5. }
  6. }
  7. }

1.2 向 Thread() 构造方法传递 Runnable 对象

  1. class MyTack implements Runnable {
  2. public void run() {
  3. }
  4. }
  5. MyTask mytask = new MyTask();
  6. Thread thread = new Thread(mytask);
  7. thread.start();

1.3 使用匿名类

  1. new Thread() {
  2. public void run() {
  3. for (int i = 0; i < 100; ++i)
  4. System.out.println(i);
  5. }
  6. }

1.4 使用 Lambda 表达式

  1. new Thread(() -> {
  2. // ...
  3. }).start();

2 线程的控制

image.png
image.png
image.png
image.png

3 线程的同步

image.png
image.png
image.png

wait()notify() 相当于操作系统中的 P 操作和 V 操作

  1. class CubbyHole {
  2. public int index = 0;
  3. publin int[] data = new int[3];
  4. public synchronized void put(int value) {
  5. while (index == data.length) {
  6. try {
  7. this.wait();
  8. } catch (InterruptedException e) {}
  9. }
  10. data[index] = value;
  11. index++;
  12. this.notify();
  13. }
  14. public synchronized int get() {
  15. while (index <= 0) {
  16. try {
  17. this.wait();
  18. } catch (InterruptedException e) {}
  19. }
  20. index--;
  21. int val = data[index];
  22. this.notify();
  23. return val;
  24. }
  25. }

image.png