Java web

Java 线程

2018-12-10  本文已影响0人  dawsonenjoy

java.lang.Thread下已经有封装好的线程类

线程的生命周期

1.新建状态(NEW)

实例化线程的时候

2.运行状态(RUNNABLE)

运行状态中又分就绪状态和可运行状态
(1)就绪状态:调用线程的start()方法之后,等待JVM调度的过程,要注意的是一个线程只能调用一次start()方法,再次调用则会报错,然后如果需要再次执行就需要重新实例化一个线程
(2)可运行状态:线程对象获得JVM调度

3.阻塞状态(BLOCKED)

线程放弃CPU分配,暂时停止运行,此时JVM不会给线程分配CPU,需等线程进入就绪状态后才能再得到分配调度

4.等待状态(WAITING)

该状态下只能等待其他线程唤醒,使用wait()方法进入该状态

5.计时等待状态(TIMED_WAITING)

进入一定时间的等待状态,使用wait(time)/Thread.sleep(time)进入该状态

6.终止状态(TERMINATED)

当执行完run()方法或遇到异常退出后的状态

创建线程

方法一

1.定义一个类继承于Thread
2.重写public void run(){}方法
3.生成该对象
举例:

public class Test {
    public static void main(String[] args){
        Count c = new Count();
        c.start();  //直接启动
        for(int i=0; i<100; i++)
            System.out.println("Main:"+i);
    }
}

class Count extends Thread {    //继承Thread
    public void run(){  //重写run()
        for(int i=0; i<100; i++)
            System.out.println("Count:"+i);
    }
}
方法二

1.定义线程类继承Runnable接口,里面只有一个public void run(){}方法
2.实例化一个线程类,然后将Runnable接口传入
其中使用Runnable接口可以为多个线程提供共享的数据,且在Runnable接口类的run方法中可以使用Thread的静态方法,如currentThread()为获取当前线程的引用
举例:

public class Test {
    public static void main(String[] args){
        Count c = new Count();  //实例化
        Thread t = new Thread(c);   //实例化线程
        t.start();  //启动线程
        for(int i=0; i<100; i++)
            System.out.println("Main:"+i);
    }
}

class Count implements Runnable {   //继承Runnable
    public void run(){  //重写run()
        for(int i=0; i<100; i++)
            System.out.println("Count:"+i);
    }
}
两种方式对比

在第一种方式中,每次都得实例化一个对象,所以每个的数据都是单独的,而且类是单继承的,此时就不能再继承其他类了,但是继承线程类后就可以直接调用其下的一些方法,操作上也就更加方便;在第二种方式中则可以实例化一个对象,然后将这一个对象放入多个线程当中,即可实现数据共享,但是因为不是继承线程类,所以没有线程类的方法控制,如果需要使用那些方法,则需要通过Thread.currentThread()来获得当前线程,然后调用那些方法。第二种线程数据共享及调用线程方法举例:

public class Test {
    public static void main(String[] args) {
        System.out.println(1);
        ThreadTest tt = new ThreadTest();
        new Thread(tt).start(); //不取名则默认名Thread-0
        new Thread(tt, "bbb").start();
        new Thread(tt, "ccc").start();
    }
}

class ThreadTest implements Runnable{
    public int i = 10;
    public void run() {
        for(;i>0;i--)
            System.out.println(Thread.currentThread().getName() + ":" + i);  //获取当前线程
    }   
}

因为三个线程都是公用i的值,所以总共也只输出10次

内部类创建线程

当线程只是一次性使用的情况下,可以使用该方式创建线程,举例:

//方法1的内部类线程创建
new Thread() {
    public void run() {
        for (int i = 0; i < 500; i++)
            System.out.println("Runnable:" + i);
    }
}.start();

//方法2的内部类线程创建
new Thread(new Runnable() {
    public void run() {
        for (int i = 0; i < 500; i++)
            System.out.println("Thread:" + i);
    }
}).start();

启动线程

使用start()方法启动一个新线程,而run()则是调用线程里的方法体,并不会启动一个新线程

线程控制方法

Thread类下的常用方法如下

getName()

获取当前线程名称

isAlive()

线程是否启动或者未终止

getPriority()

获取线程优先级数值

setPriority()

设置线程优先级数值,优先级越高,那么分配到的时间片越多,其中优先级范围为1~10,默认为5,一些优先级常量:

Thread.MIN_PRIORITY = 1
Thread.MAX_PRIORITY = 10
Thread.NORM_PRIORITY = 5
sleep()

线程睡眠多少毫秒,一旦睡眠期间被打断则会抛出InterruptedException异常

interrupt()

打断线程

join()

将当前线程与该线程合并,即把join的线程先执行完再执行当前线程,会抛出InterruptException,例如在main函数:

Count c = new Count();
c.start();
try{
    c.join();
}catch(InterruptedException e){
    ;
}

于是会先把c线程的内容执行完然后继续执行主线程

setDaemon()

设置守护线程,此时只要主线程没结束,该线程就不会结束,必须在线程启动前设置,举例:

Thread thread = new Thread(new Runnable() {
    public void run() {
        for (int i = 0; i < 100; i++)
            System.out.println(Thread.currentThread().getName() + ":" + i);
    }
});
thread.setDaemon(true); // 设置守护线程
thread.start();
isDaemon()

判断是否为守护线程

yield()

让出CPU,让线程进入就绪队列等待调度,举例:

public void run(){
    for(int i=0; i<100; i++){
        System.out.println("Count:"+i);
        if(i%10 == 0)
            yield();    //当i为10的倍数时让给别的线程调度
    }
}
wait()

让当前线程进入对象的等待池,释放同步锁,如果无参则是永久等待,有参则可以设置等待时间。要注意的是这个和下面的notify()方法都是java.lang.Object下的方法,而不是Thread下的方法,并且需要在同步锁的情况下才有用,即synchronized (this){}包着才行

notify()/notifyAll()

唤醒等待池的任意一个/所有等待线程,结合该方法和上面的方法,基本的生产者消费者模型如下:

public class Test {
    public static void main(String[] args) throws Exception {
        Resource r = new Resource();
        new Thread(new Producer(r), "Producer").start(); // 生产者
        new Thread(new Consumer(r), "Consumer1").start(); // 消费者
        new Thread(new Consumer(r), "COnsumer2").start(); // 消费者
    }
}

class Resource {
    int num = 0;

    synchronized public void push() {
        try {
            if (num >= 5) { // 当数量大于5个时进入等待
                this.wait();
            }
            System.out.println(Thread.currentThread().getName() + ":+1,"
                    + ++num);
            Thread.sleep(1000);
            this.notifyAll(); // 唤醒所有消费者线程

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

    synchronized public void pop() {
        while (num <= 0) { // 当数量大于0的时候取出,否则线程等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + ":-1," + --num);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.notifyAll(); // 唤醒生产者线程
    }
}

class Producer implements Runnable {
    Resource r = null;

    public Producer(Resource r) {this.r = r;}

    public void run() {
        while (true)
            this.r.push();
    }
}

class Consumer implements Runnable {
    Resource r = null;

    public Consumer(Resource r) {this.r = r;}

    public void run() {
        while (true)
            this.r.pop();
    }
}
stop()

杀死线程,基本已经被废弃的方法

同步问题

当程序执行时可能会因为线程的同步机制而导致一些问题,比如下面的代码:

public class Test {
    public static void main(String[] args) {
        Count c1 = new Count();
        Count c2 = new Count();
        c1.start();
        c2.start();
    }
}

class Count extends Thread{
    static int num = 0; //计数变量
    public void run(){
        num++;  //执行自增后休眠一秒
        try{
            Thread.sleep(1000);
        }catch (InterruptedException e) {
            ;
        }
        System.out.println(getName() + ":" + num);
    }
}
结果为:
Thread-1:2
Thread-0:2

可以发现两个并非一个是1一个是2,而都是2,这是因为第一个自增后休眠,于是第二个也对num进行了自增,结果导致输出时数据都为2,因此为了防止这种问题,在执行该部分(自增+休眠)时我们不应该让另一个线程掺合进来,所以需要对这块加一个同步锁(保证同一时间内只允许一个线程执行的代码块)。

同步修饰符

使用synchronize(当前对象类型){}来将某一部分代码块包起来即可实现互斥,举例对上面的类进行修改:

class Count extends Thread{
    static int num = 0;
    public void run(){
        System.out.println(getName());  //这里不会互斥
        synchronized (this.getClass()) {    //这块会互斥,用Count.class也行
        num++;
        try{Thread.sleep(1000);}
        catch (InterruptedException e) {}
        System.out.println(getName() + ":" + num);
        }
    }
}
结果为:
Thread-0
Thread-1
Thread-0:1
Thread-1:2

要注意这里的两个线程里是不同的实例化对象,所以用synchronized (this.getClass())对其进行互斥,即对当前对象设置同步锁,如果是对同一个对象进行互斥则直接synchronize(this)就行了,举例:

public class Test {
    public static void main(String[] args) {
        Count c1 = new Count();
        Thread t1 = new Thread(c1);
        Thread t2 = new Thread(c1); //同一个c1
        t1.start();
        t2.start();
    }
}

class Count implements Runnable{
    static int num = 0;
    public void run(){
        System.out.println(Thread.currentThread().getName());
        synchronized (this) {  //用Count.class也行
            num++;
            try{Thread.sleep(1000);}
            catch (InterruptedException e) {}
            System.out.println(Thread.currentThread().getName() + ":" + num);   
    }
    }
}
结果为:
Thread-0
Thread-1
Thread-0:1
Thread-1:2

注:
synchronized虽然安全,但是性能损耗更低,所以尽量减少其的作用域,原来的ArrayList/VectorHashMap/HashTableStringBuilder/StringBuffer等一个效率高,一个更安全,其主要区别就是是否有使用synchronized修饰符

同步方法

synchronized修饰的方法,对于非静态方法,同步锁就是this;对于静态方法,则使用当前方法所在类的字节码对象,即类.class
线程执行的就是run()方法,如果给该方法加上同步修饰符,那么整个run()方法期间都无法执行其他线程,也就相当于单线程了,因此不要给run()方法添加同步修饰符。一般都是给要同步的部分单独写一个方法,然后加上同步修饰符

同步锁

java.util.concurrent.locks下提供了同步锁的接口Lock,是比同步修饰符有更多功能

lock()/unlock()

获取锁/释放锁,举例:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test {
    public static void main(String[] args) throws Exception {
        ThreadTest tt = new ThreadTest();
        new Thread(tt, "aaa").start();
        new Thread(tt, "bbb").start();
        new Thread(tt, "ccc").start();
    }
}

class ThreadTest implements Runnable {
    public int num = 100;
    public final Lock lock = new ReentrantLock();   //先定义同步锁

    public void run() {
        for (int i = 0; i < 100; i++) {
            // synchronized (this) {
            lock.lock();    //换成lock()同步锁
            try {
                if (num > 0) {
                    System.out.println(Thread.currentThread().getName() + ":" + num);
                    Thread.sleep(100);
                    num--;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();  //最后记得关闭锁
            }
            // }
        }
    }
}
newCondition()

返回一个Condition接口对象,用来监视线程,里面有await()/signal()/signalAll()方法用来替代wait()/notify()/notifyAll()方法,举例:

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class test {
    static int num = 100;
    static int flag = 1;
    static Lock lock = new ReentrantLock();  //一个锁
    static Condition c1 = lock.newCondition();  //三个监视器
    static Condition c2 = lock.newCondition();
    static Condition c3 = lock.newCondition();

    public static void main(String[] args) throws Exception {
        new Thread() {
            public void run() {
                while (true)
                    print1();
            };
        }.start();
        new Thread() {
            public void run() {
                while (true)
                    print2();
            };
        }.start();
        new Thread() {
            public void run() {
                while (true)
                    print3();
            };
        }.start();

    }

    public static void print1() {
        lock.lock();
        while(flag != 1) {
            try {
                c1.await();  //等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if(num == 0){
            System.exit(0);
        }
        System.out.println("1:" + --num);
        flag = 2;
        c2.signalAll();  //唤醒
        lock.unlock();
    }

    public static void print2() {
        lock.lock();
        while(flag != 2) {
            try {
                c2.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if(num == 0){
            System.exit(0);
        }
        System.out.println("2:" + --num);
        flag = 3;
        c3.signalAll();
        lock.unlock();
    }

    public static void print3() {
        lock.lock();
        while(flag != 3) {
            try {
                c3.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if(num == 0){
            System.exit(0);
        }
        System.out.println("3:" + --num);
        flag = 1;
        c1.signalAll();
        lock.unlock();
    }
}
await()

相当于wait()

signal()/signalAll()

相当于notify()/notifyAll()

线程组

使用ThreadGroup类来创建线程组对象,默认情况下所有线程都属于主线程组

getThreadGroup()

线程下的方法,用于获取线程对象所属组,其下还有getName()方法用于获取线程名,举例:

Thread t = new Thread(new ThreadTest());
System.out.println(t.getThreadGroup().getName());  //main
Thread(ThreadGroup, thread)

线程的实例化方法当中支持传入线程组和线程,此时该线程就会被加入到指定的线程组,举例:

ThreadGroup tg = new ThreadGroup("no-main");
Thread t = new Thread(tg, new ThreadTest());
System.out.println(t.getThreadGroup().getName());   //no-main

线程池

通过ExecutorService来存储线程池对象,通过ExecutorsnewFixedThreadPool(int)方法创建一定数量的线程池

submit()

将线程放入线程池并执行,举例:

ExecutorService pool = Executors.newFixedThreadPool(2);  //线程池里有2个线程
Thread t1 = new Thread(new ThreadTest());
pool.submit(t1);
pool.submit(t1);

结果:
pool-1-thread-1
pool-1-thread-2
shutdown()

上面的代码执行结束后,线程池并没有关闭,所以需要该方法来关闭线程池

上一篇 下一篇

猜你喜欢

热点阅读