多线程编程

1.区分线程与进程

线程:基于线程的多任务处理器中,线程为最小的处理单位,【特点】是进程内部单一的一个顺序控制流。

进程:指正在被运行的程序。每个进程都有自己独立的一块内存空间,每个进程的内部数据和状态都是完全独立的。

二者区别:线程存在于进程之中。每个进程都需要操作系统为其分配独立的内存空间,二同一进程中的所有线程都在同一内存空间中工作,这些线程可以共享同一内存和系统资源。

2.线程编程相关API

核心类:Thread类、Object类...

接口:Runnable接口...

A:Thread类中的方法

           1). interrup:中断线程。

           2).run:如果该线程是使用独立的 Runnable 运行对象构造的,则调用该 Runnable 对象的 run 方法;否则,该方法不执行任何操作并返回。 

               Thread 的子类应该重写该方法。

           3).start:使该线程开始执行;Java 虚拟机调用该线程的 run 方法。

           4). yield:暂停当前正在执行的线程对象,并执行其他线程。

           5). sleep:在指定的毫秒数内让当前正在执行的线程休眠(暂停执行),此操作受到系统计时器和调度程序精度和准确性的影响。

           6). join:让其他线程插入本线程之前。

           7).wait:在其他线程调用此对象的 notify() 方法或 notifyAll() 方法前,导致当前线程等待。

           8). notify:唤醒在此对象监视器上等待的单个线程。

           9).notifyAll:唤醒在此对象监视器上等待的所有线程。

            .......

B:Runnable接口

     只定义了一个方法run()

C:Object类

           1).wait:就是使当前线程等待该对象的锁,当前线程必须是该对象的拥有者,也就是具有该对象的锁。wait()方法一直等待,直到获得锁或者被中断。wait(long timeout)                设定一个超时间隔,如果在规定时间内没有获得锁就返回。

               调用该方法后当前线程进入睡眠状态,直到以下事件发生。

                a:其他线程调用了该对象的notify方法。

                b:其他线程调用了该对象的notifyAll方法。

                c:其他线程调用了interrupt中断该线程。

                d:时间间隔到了。

               此时该线程就可以被调度了,如果是被中断的话就抛出一个InterruptedException异常。

           2).notify:该方法唤醒在该对象上等待的某个线程。

           3).notifyAll:该方法唤醒在该对象上等待的所有线程。

3.线程的优先级

例:

public class Main {

    /**
     * Starts two threads, setting priorities on them 
     * and wait for them to finish.
     * 
     */
    public void setPrioritiesOnThreads() {

        Thread thread1 = new Thread(new TestThread(1));
        Thread thread2 = new Thread(new TestThread(2));

        //Setting priorities on the Thread objects
        thread1.setPriority(Thread.MAX_PRIORITY);
        thread2.setPriority(Thread.MIN_PRIORITY);

        thread1.start();
        thread2.start();

        try {

            //Wait for the threads to finish
            thread1.join();
            thread2.join();

        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }

        System.out.println("Done.");

    }
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().setPrioritiesOnThreads();
    }

    class TestThread implements Runnable {

        int id;

        public TestThread(int id) {

            this.id = id;
        }

        public void run() {

            for (int i = 1; i <= 10; i++) {
                System.out.println("Thread" + id + ": " + i);
            }
        }
    }
}

4.线程的生命周期

原文地址:https://www.cnblogs.com/moshengren-java/p/4458084.html