Java多线程机制

    |     2015年4月10日   |   多线程编程   |     0 条评论   |    1698

线程是一个程序内部的顺序控制流:一个进程相当于一个任务,一条线程相当于这个任务里的一条执行路径。多进程是操作系统同时跑多个程序;多线程是同一个应用程序里有多条顺序流同时执行。Java 的线程通过 java.lang.Thread 实现。

JVM 启动时会有一个由 public static void main() 定义的线程。可以 new Thread 实例来创建新线程;每个线程靠对应对象的 run() 完成工作(线程体),调用 start() 才会真正启动。

方式 怎么做 特点
实现 Runnable new Thread(target),target 是 Runnable 多个线程可共享同一份数据
继承 Thread 子类重写 run(),再 new 子类对象 占用了唯一的继承名额

一、创建和启动

第一种:定义类实现 Runnable;Runnable 只有一个方法 public void run(),用来写线程体。run 里可用 Thread.currentThread() 拿到当前线程引用。

第二种:定义 Thread 的子类并重写 run:

class MyThread extends Thread {
    public void run() {
        // 线程体
    }
}
MyThread myThread = new MyThread();

二、线程控制的基本方法

  • isAlive():线程是否还“活”着。
  • getPriority() / setPriority():读写优先级。
  • Thread.sleep():当前线程睡眠指定毫秒。
  • join():当前线程等待该线程结束再继续。
  • yield():让出 CPU,进入就绪队列等待调度。
  • wait():当前线程进入对象的 wait pool。
  • notify() / notifyAll():唤醒 wait pool 中一个 / 全部等待线程。

三、线程间通信:生产者消费者

用产品盒(容量 6)说明 wait / notify:满了生产者 wait,空了消费者 wait;对方操作后 notify。push / pop 都加 synchronized,条件用 while 判断,避免被唤醒后状态已经变了还继续干。

public class ProducerConsumer {
    public static void main(String[] args) {
        ProductBox pb = new ProductBox();
        Thread pThread = new Thread(new Producer(pb));
        Thread cThread = new Thread(new Consumer(pb));
        pThread.setPriority(Thread.MAX_PRIORITY);
        pThread.start();
        cThread.start();
    }
}

class Product {
    int id;
    public Product(int id) { this.id = id; }
    public String toString() { return "Product:" + id; }
}

class ProductBox {
    Product[] productbox = new Product[6];
    int index = 0;

    public synchronized void push(Product p) {
        while (index == productbox.length) {
            try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); }
        }
        this.notify();
        productbox[index] = p;
        index++;
    }

    public synchronized Product pop() {
        while (index == 0) {
            try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); }
        }
        this.notify();
        index--;
        return productbox[index];
    }
}

class Producer implements Runnable {
    ProductBox productbox;
    public Producer(ProductBox productbox) { this.productbox = productbox; }
    public void run() {
        for (int i = 0; i < 10; i++) {
            Product p = new Product(i);
            productbox.push(p);
            System.out.println("produce:" + p);
            try { Thread.sleep((int) (Math.random() * 200)); } catch (InterruptedException e) { e.printStackTrace(); }
        }
    }
}

class Consumer implements Runnable {
    ProductBox productbox;
    public Consumer(ProductBox productbox) { this.productbox = productbox; }
    public void run() {
        for (int i = 0; i < 10; i++) {
            Product p = productbox.pop();
            System.out.println("consume:" + p);
            try { Thread.sleep((int) (Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); }
        }
    }
}

一句话总结:线程是进程里的一条执行路径,run 是线程体、start 才启动;共享数据用 Runnable,协作靠 synchronized + wait/notify,条件判断用 while。

转载请注明来源:Java多线程机制
本文链接地址:https://ai.zhousir.top/?p=162
回复 取消