Java多线程

Java线程学习详解

2019-11-08  本文已影响0人  开始以后_

线程基础

1. 线程的生命周期

1.1 新建状态:

1.2 就绪状态:

1.3 运行状态:

1.4 阻塞状态:

1.5 死亡状态:

2. 线程的优先级和守护线程

2.1 线程的优先级

2.2 守护线程

3. 创建线程

3.1 通过实现 Runnable 接口

3.2 通过继承 Thread 类本身

3.3 通过 Callable 和 Future 创建线程

4. synchronized关键字

4.1 概述

4.2 基本原则

4.3 实例

4.4 synchronized方法和synchronized代码块

4.4.1 概述

4.4.2 实例

public class SnchronizedTest {

    public static void main(String[] args) {

        class Demo {
            // synchronized方法
             public synchronized void synMethod() {
                    for(int i=0; i<1000000; i++)
                        ;
                }
                
                public void synBlock() {
                    // synchronized代码块
                    synchronized( this ) {
                        for(int i=0; i<1000000; i++)
                            ;
                    }
                }
        }
    }
}

4.5 实例锁和全局锁

4.5.1 概述

4.5.2 实例

pulbic class Something {
    public synchronized void isSyncA(){}
    public synchronized void isSyncB(){}
    public static synchronized void cSyncA(){}
    public static synchronized void cSyncB(){}
}

假设,类Something有两个实例(对象)分别为x和y。分析下面4组表达式获取锁的情况。

5. Volatile 关键字

5.1 Volatile原理

6. 线程等待和唤醒

6.1 常用方法

6.2 实例

package com.ljw.thread;

public class WaitDemo {
    public static void main(String[] args) {

        class ThreadTest extends Thread{
            
            @Override
            public void run() {
                synchronized (this) {
                    System.out.println("开始运行线程 "+Thread.currentThread().getName());
                    System.out.println("唤醒线程notify()");
                    notify();
                }
            }
        }
        
        ThreadTest thread1 = new ThreadTest();
        thread1.start();
        
        synchronized (thread1) {
            try {
                System.out.println("主线程进入阻塞,释放thread对象的同步锁,wait()");
                thread1.wait(); // wait()是让当前线程进入阻塞状态,wait()是在主线程中执行,
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("主线程继续进行");
    }
}

7. 线程让步和休眠

7.1 线程让步

7.1.1 概述

7.1.2 实例

package com.ljw.thread;

public class YieldTest {

    public static void main(String[] args) {

        class ThreadA extends Thread{
            public ThreadA(String name){
                super(name);
            }
            
            @Override
            public synchronized void run() {

                for(int i=0;i<5;i++){
                    System.out.println(" "+this.getName()+" "+i);
                    
                    if(i%2 == 0){
                        Thread.yield();
                    }
                }
            }
        }
        
        ThreadA t1 = new ThreadA("t1");
        ThreadA t2 = new ThreadA("t2");
        t1.start();
        t2.start();
    }
}

运行结果(不唯一):

 t1 0
 t2 0
 t1 1
 t1 2
 t2 1
 t1 3
 t2 2
 t1 4
 t2 3
 t2 4

结果说明:
线程t1在能被2整除的时候,并不一定切换到线程2。这表明,yield()方法虽然可以让线程由“运行状态”进入到“就绪状态”;但是,它不一定会让其他线程获取CPU执行权(其他线程进入到“运行状态”)。即时这个“其他线程”与当前调用yield()的线程具有相同的优先级。

7.1.3 yield()和wait()比较

7.2 线程休眠

7.2.1 概述

7.2.2 sleep() 和 wait()的比较

8. 加入一个线程

8.1 概述

9. 终止一个线程

9.1 概述

@Override
public void run() {
    try {
        // 1. isInterrupted()保证,只要中断标记为true就终止线程。
        while (!isInterrupted()) {
            // 执行任务...
        }
    } catch (InterruptedException ie) {  
        // 2. InterruptedException异常保证,当InterruptedException异常产生时,线程被终止。
    }
}

9.2 实例

public class InterruptBlock {

    /**
     * @param args
     */
    public static void main(String[] args) {
    
        class MyThread extends Thread{
            public MyThread(String name){
                super(name);
            }
            
            @Override
            public void run() { 
                try {
                    int i=0;
                    while(!isInterrupted()){
                         Thread.sleep(100);
                         i++;
                         System.out.println(Thread.currentThread().getName()+ " ("+this.getState()+") loop "+i);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println(Thread.currentThread().getName()+ " ("+this.getState()+") catch InterruptedExecption");
                }   
            }
        }
        
        
        try {
            
            //新建
            Thread t1 = new MyThread("t1");
            System.out.println(t1.getName()+" ("+t1.getState()+" ) is new.");
            
            System.out.println("luo1:"+t1.isInterrupted());
            //启动
            t1.start();
            System.out.println(t1.getName()+" ("+t1.getState()+" ) is started.");
            System.out.println("luo2:"+t1.isInterrupted());
            //主线程休眠300ms,然后主线程给t1发“中断”指令
            Thread.sleep(300);
            t1.interrupt();
            System.out.println("luo3:"+t1.isInterrupted());
            System.out.println(t1.getName()+" ("+t1.getState()+" ) is interrupted.");
            
            //主线程休眠300ms,然后查看t1的状态
            Thread.sleep(300);
            System.out.println(t1.getName()+" ("+t1.getState()+" ) is interrupted now .");
            
            
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

}

运行结果:

t1 (NEW ) is new.
luo1:false
t1 (RUNNABLE ) is started.
luo2:false
t1 (RUNNABLE) loop 1
t1 (RUNNABLE) loop 2
luo3:true
t1 (RUNNABLE) loop 3
t1 (RUNNABLE ) is interrupted.
t1 (TERMINATED ) is interrupted now .

9.3 interrupt()和isInterrupted()的区别

线程进阶

1. 线程池

package com.ljw.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolDemo {
 
    public static void main(String[] args) { // 主线程
        // 线程池 ---> Executors工具类(工厂类)
        /*
         * newFixedThreadPool(int threadCount) 创建固定数量的线程池
         * newCachedThreadPool() 创建动态数量的线程池
         */
        ExecutorService es = Executors.newFixedThreadPool(3);
        
        Runnable task = new MyTask();
        
        // 提交任务
        es.submit(task); 
        es.submit(task);
        
        es.shutdown(); // 关闭线程池,则表示不在接收新任务,不代表正在线程池的任务会停掉
    }   
}

class MyTask implements Runnable{

    @Override
    public void run() {
        for(int i=0;i<100;i++) {
            System.out.println(Thread.currentThread().getName()+" MyTask "+i);
        }
    }
}

2. 线程安全与锁

2.1 重入锁和读写锁

package com.ljw.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

/**
 * ReentrantLock类,重入锁:Lock接口的实现类,与synchronized一样具有互斥锁功能 lock() 和 unlock()
 * ReentrantReadWriteLock类,读写锁:一种支持一写多读的同步锁,读写分离,分别分配读锁和写锁,在读操作远远高于写操作的环境中可以提高效率
 *      互斥规则:
 *          写--写:互斥,阻塞
 *          读--写:互斥,阻塞
 *          读--读:不互斥,不阻塞
 *
 */

public class LockDemo {

    public static void main(String[] args) {
        ExecutorService es = Executors.newFixedThreadPool(20);
        Student s = new Student();
//      ReentrantLock rLock = new ReentrantLock(); // 用ReenTrantLock加锁运行时间20008ms
        ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); // 用读写锁分别对读写任务加锁运行时间3003ms
        ReadLock rl = rwLock.readLock();
        WriteLock wl = rwLock.writeLock();
        
        // 写任务
        Callable<Object> writeTask = new Callable<Object>() {

            @Override
            public Object call() throws Exception {
//              rLock.lock();
                wl.lock();
                try {
                    Thread.sleep(1000);
                    s.setValue(100);
                }finally {
//                  rLock.unlock();
                    wl.unlock();
                }
                
                return null;
            }};
        
        // 读任务
        Callable<Object> readTask = new Callable<Object>() {

            @Override
            public Object call() throws Exception {
//              rLock.lock();
                rl.lock();
                try {
                    Thread.sleep(1000);
                    s.getValue();
                }finally {
//                  rLock.unlock();
                    rl.unlock();
                }               
                return null;
            }};

        // 开始时间
        long start = System.currentTimeMillis();
        for(int i=0;i<2;i++) { // 写任务执行 2 次
            es.submit(writeTask);
        }
        for(int i=0;i<18;i++) { // 读任务执行 18 次
            es.submit(readTask);
        }
        
        es.shutdown(); // 停止线程池,不在接受新的任务,将现有任务全部执行完毕
        
        while(true) {
            if(es.isTerminated()) { // 当线程池中所有任务执行完毕,返回true,否则返回false
                break;
            }
        }
        
        // 执行到这里,说明线程池中所有任务都执行完毕,可以计算结束时间
        System.out.println(System.currentTimeMillis()-start);
    
    }
}

class Student {
    private int value;
    
    //读
    public int getValue() {
        return value;
    }
    
    //写
    public void setValue(int value) {
        this.value = value;
    }
}

2.2 线程安全

2.2.1 Collections工具类

static <T> Collection<T> synchronizedCollection(Collection<T> c) 
    //返回由指定集合支持的同步(线程安全)集合。  
static <T> List<T> synchronizedList(List<T> list) 
    //返回由指定列表支持的同步(线程安全)列表。  
static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) 
    //返回由指定地图支持的同步(线程安全)映射。  
static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m) 
    //返回由指定的可导航地图支持的同步(线程安全)可导航地图。  
static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s) 
    //返回由指定的可导航集支持的同步(线程安全)可导航集。  
static <T> Set<T> synchronizedSet(Set<T> s) 
    //返回由指定集合支持的同步(线程安全)集。  
static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) 
    //返回由指定的排序映射支持的同步(线程安全)排序映射。  
static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) 
     //返回由指定的排序集支持的同步(线程安全)排序集。

2.2.2 CopyOnWriteArrayList

2.2.3 CopyOnWriteArraySet

2.2.4 ConcurrentHashMap

上一篇下一篇

猜你喜欢

热点阅读