Java中线程的相关知识整理

2018/05/10 Java

Java中线程的相关知识整理

线程的概念

程序:program,是一个静态的概念
进程:progress,是一个动态的概念
  • 进程是程序的一次动态执行过程,占用特定的地址空间
  • 每个进程都是独立的,由3部分组成cpu,data,code
  • 缺点:内存的浪费,cpu的负担
线程:Thread,是进程中一个“单一的连续控制流程”/执行路径
  • 线程又被称为轻量级进程
  • 一个进程可拥有多个并行的线程
  • 一个进程中的线程共享相同的内存单元/内存地址空间->可以访问相同的变量和对象,而且它们从同一堆中分配对象->通信、数据交换、同步操作。
  • 由于线程间的通信是在同一地址空间上进行的,所以不需要额外的通信机制,这就使得通信更简便而且信息传递速度也更快。

线程和进程的区别

image

Java中实现多线程

  • 在Java中负责线程的这个功能的是Java.lang.Thread这个类
  • 可以同创建Thread的实例来创建新的线程
  • 每个线程都是通过某个特定Thread对象所对应的方法run()来完成其操作的,方法run()称为线程体
  • 通过调用Thread类的start()方法类启动一个线程体
  • 继承Thread类方式的缺点:那就是如果我们的类已经从一个类继承,则无法再继承Thread类
/** 
 * 模拟龟兔赛跑 
 1、创建多线程  继承  Thread  +重写run(线程体) 
 2、使用线程: 创建子类对象 + 调用对象.start()方法    线程启动 
 * @author W.Sky 
 * 
 */  
public class Rabbit extends Thread {  
      
    @Override  
    public void run() {  
        //线程体  
        for(int i=0;i<100;i++){  
            System.out.println("兔子跑了"+i+"步");  
        }  
          
    }  
      
}  
  
class Tortoise extends Thread {  
  
    @Override  
    public void run() {  
        //线程体  
        for(int i=0;i<100;i++){  
            System.out.println("乌龟跑了"+i+"步");  
        }  
          
    }  
      
}  
  • 通过Runnable接口实现多线程

  • 优点:可以同时实现继承,实现Runnable接口方式要通用一些

    1)避免单继承

    2)方便共享资源,同一份资源,多个代理访问

/** 
 推荐  Runnable 创建线程 
 1)、避免单继承的局限性 
 2)、便于共享资源 
   
   
  使用 Runnable 创建线程 
  1、类 实现 Runnable接口 +重写 run()   -->真实角色类 
  2、启动多线程  使用静态代理 
    1)、创建真实角色 
    2)、创建代理角色 +真实角色引用 
    3)、调用 .start() 启动线程 
   
   
 * @author W.Sky 
 * 
 */  
public class Programmer implements Runnable {  
  
    @Override  
    public void run() {  
        for(int i=0;i<1000;i++){  
            System.out.println("一边敲helloworld....");  
        }  
    }  
  
  
} 
/** 
 推荐  Runnable 创建线程 
 1)、避免单继承的局限性 
 2)、便于共享资源 
   
   
  使用 Runnable 创建线程 
  1、类 实现 Runnable接口 +重写 run()   -->真实角色类 
  2、启动多线程  使用静态代理 
    1)、创建真实角色 
    2)、创建代理角色 +真实角色引用 
    3)、调用 .start() 启动线程 
   
   
 * @author W.Sky 
 * 
 */  
public class Programmer implements Runnable {  
  
    @Override  
    public void run() {  
        for(int i=0;i<1000;i++){  
            System.out.println("一边敲helloworld....");  
        }  
    }  
  
  
} 
  • 通过Callable接口实现多线程
  • 优点:可以获取返回值
  • 缺点:繁琐
import java.util.concurrent.Callable;  
import java.util.concurrent.ExecutionException;  
import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
import java.util.concurrent.Future;  
/** 
 * 使用Callable创建线程 
 * @author W.Sky 
 * 
 */  
public class Call {  
    public static void main(String[] args) throws InterruptedException, ExecutionException {  
        //创建线程  
        ExecutorService  ser=Executors.newFixedThreadPool(2);  
        Race tortoise = new Race("老不死",1000);  
        Race rabbit = new Race("小兔子",500);  
        //获取值  
        Future<Integer> result1 =ser.submit(tortoise) ;  
        Future<Integer> result2 =ser.submit(rabbit) ;  
          
        Thread.sleep(2000); //2秒  
        tortoise.setFlag(false); //停止线程体循环  
        rabbit.setFlag(false);  
          
        int num1 =result1.get();  
        int num2 =result2.get();  
        System.out.println("乌龟跑了-->"+num1+"步");  
        System.out.println("小兔子跑了-->"+num2+"步");  
        //停止服务   
        ser.shutdownNow();  
  
    }  
}  
  
class Race implements Callable<Integer>{  
    private String name ; //名称  
    private long time; //延时时间  
    private boolean flag =true;  
    private int step =0; //步  
    public Race() {  
    }     
  
    public Race(String name) {  
        super();  
        this.name = name;  
    }  
    public Race(String name,long time) {  
        super();  
        this.name = name;  
        this.time =time;  
    }  
  
    @Override  
    public Integer call() throws Exception {  
        while(flag){  
            Thread.sleep(time); //延时  
            step++;  
        }  
        return step;  
    }  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
      
  
    public long getTime() {  
        return time;  
    }  
  
    public void setTime(long time) {  
        this.time = time;  
    }  
  
    public boolean isFlag() {  
        return flag;  
    }  
  
    public void setFlag(boolean flag) {  
        this.flag = flag;  
    }  
  
    public int getStep() {  
        return step;  
    }  
  
    public void setStep(int step) {  
        this.step = step;  
    }  
      
}  

线程的状态

  • 新生状态
  • 就绪状态
  • 运行状态
  • 阻塞状态
  • 死亡状态
/** 
 * join:合并线程 
 * @author W.Sky 
 * 
 */  
public class JoinDemo01 extends Thread {  
  
    public static void main(String[] args) throws InterruptedException {  
        JoinDemo01 demo = new JoinDemo01();  
        Thread t = new Thread(demo); //新生  
        t.start();//就绪  
        //cpu调度 运行  
          
          
        for(int i=0;i<1000;i++){  
            if(50==i){  
                t.join(); //main阻塞...  
            }  
            System.out.println("main...."+i);  
        }  
    }  
      
    @Override  
    public void run() {  
        for(int i=0;i<1000;i++){  
            System.out.println("join...."+i);  
        }  
    }  
  
}  
Sleep模拟网络延时
/** 
 * Sleep模拟 网络延时  线程不安全的类 
 * @author W.Sky 
 * 
 */  
public class SleepDemo02 {  
  
    public static void main(String[] args) {  
        //真实角色  
        Web12306 web= new Web12306();  
        Web12306 web2 = new Web12306();  
        //代理  
        Thread t1 =new Thread(web,"路人甲");  
        Thread t2 =new Thread(web,"黄牛已");  
        Thread t3 =new Thread(web,"攻城师");  
        //启动线程  
        t1.start();  
        t2.start();  
        t3.start();  
    }  
  
}  
  
class Web12306 implements Runnable {  
    private int num =50;  
  
    @Override  
    public void run() {  
        while(true){  
            if(num<=0){  
                break; //跳出循环  
            }  
            try {  
                Thread.sleep(500);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
            System.out.println(Thread.currentThread().getName()+"抢到了"+num--);  
        }  
    }  
      
}  

线程基本信息

image

  • 优先级:表达的是概率,不是绝对的先后顺序
/** 
 * 
  Thread.currentThread()     :当前线程 
  setName():设置名称 
  getName():获取名称 
  isAlive():判断状态 
 
 * @author W.Sky 
 * 
 */  
public class InfoDemo01 {  
  
    public static void main(String[] args) throws InterruptedException {  
        MyThread it =new MyThread();  
        Thread proxy =new Thread(it,"挨踢");  
        proxy.setName("test");  
        System.out.println(proxy.getName());  
        System.out.println(Thread.currentThread().getName()); //main  
          
        proxy.start();  
        System.out.println("启动后的状态:"+proxy.isAlive());  
        Thread.sleep(200);  
        it.stop();  
        Thread.sleep(100);  
        System.out.println("停止后的状态:"+proxy.isAlive());  
    }  
  
}  
/** 
 * 
  Thread.currentThread()     :当前线程 
  setName():设置名称 
  getName():获取名称 
  isAlive():判断状态 
 
 * @author W.Sky 
 * 
 */  
public class InfoDemo01 {  
  
    public static void main(String[] args) throws InterruptedException {  
        MyThread it =new MyThread();  
        Thread proxy =new Thread(it,"挨踢");  
        proxy.setName("test");  
        System.out.println(proxy.getName());  
        System.out.println(Thread.currentThread().getName()); //main  
          
        proxy.start();  
        System.out.println("启动后的状态:"+proxy.isAlive());  
        Thread.sleep(200);  
        it.stop();  
        Thread.sleep(100);  
        System.out.println("停止后的状态:"+proxy.isAlive());  
    }  
  
}  

线程同步

  • 由于同一进程的多个线程共享同一片存储空间,在带来方便的同时,也带来了访问冲突这个严重的问题。Java语言提供了专门机制以解决这种冲突,有效避免了同一数据对象被多个线程同时访问。

  • 由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种用法:synchronized方法和synchronized块。

/** 
 * 过多的同步方法可能造成死锁 
 * @author W.Sky 
 * 
 */  
public class SynDemo03 {  
  
    public static void main(String[] args) {  
        Object g =new Object();  
        Object m = new Object();  
        Test t1 =new Test(g,m);  
        Test2 t2 = new Test2(g,m);  
        Thread proxy = new Thread(t1);  
        Thread proxy2 = new Thread(t2);  
        proxy.start();  
        proxy2.start();  
    }  
  
}  
class Test implements Runnable{  
    Object goods ;  
    Object money ;  
      
    public Test(Object goods, Object money) {  
        super();  
        this.goods = goods;  
        this.money = money;  
    }  
  
    @Override  
    public void run() {  
        while(true){  
            test();  
        }  
    }  
      
    public void test(){  
        synchronized(goods){  
            try {  
                Thread.sleep(100);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
            synchronized(money){  
                  
            }  
              
        }  
        System.out.println("一手给钱");  
    }  
      
  
}  
  
class Test2  implements Runnable{  
    Object goods ;  
    Object money ;  
    public Test2(Object goods, Object money) {  
        super();  
        this.goods = goods;  
        this.money = money;  
    }  
  
    @Override  
    public void run() {  
        while(true){  
            test();  
        }  
    }  
      
    public void test(){  
        synchronized(money){  
            try {  
                Thread.sleep(100);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
            synchronized(goods){  
                  
            }  
              
        }  
        System.out.println("一手给货");  
    }  
  
      
}  

生产者消费者模式

  • 生产者消费者问题,也称有限缓冲问题,是一个多线程同步问题的经典案例。该问题描述了两个共享固定大小缓冲区的线程——即所谓的“生产者”和“消费者”——在实际运行时会发生的问题。生产者主要的作用是生成一定量的数据放到缓冲区中,然后重复此过程。与此同时,消费者也在缓冲区中消耗这些数据。该问题的关键就是要保证生产者不会在缓冲区满时加入数据,消费者也不会在缓冲区空时消耗数据。

  • 要解决该问题,就必须让生产者在缓冲区满时休眠,等到下次消费者消耗缓冲区中数据的时候,生产者才能被唤醒,开始往缓冲区添加数据。同样,也可以让消费者在缓冲区空时进入休眠,等到生产者往缓冲区添加数据之后,再唤醒消费者。通常常用的方法有信号灯法、管程灯。如果解决方法不够完善,则容易出现死锁的情况。出现死锁时,两个线程都会陷入休眠,等待对方唤醒自己。

/** 
 一个场景,共同的资源 
  生产者消费者模式 信号灯法 
 wait() :等待,释放锁   sleep 不释放锁 
 notify()/notifyAll():唤醒 
  与 synchronized 
 * @author W.Sky 
 * 
 */  
public class Movie {  
    private String pic ;  
    //信号灯  
    //flag -->T 生产生产,消费者等待 ,生产完成后通知消费  
    //flag -->F 消费者消费 生产者等待, 消费完成后通知生产  
    private boolean flag =true;  
  
    public synchronized void play(String pic){  
        if(!flag){ //生产者等待  
            try {  
                this.wait();  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  
        //开始生产  
        try {  
            Thread.sleep(500);  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
        System.out.println("生产了:"+pic);  
        //生产完毕        
        this.pic =pic;  
        //通知消费  
        this.notify();  
        //生产者停下  
        this.flag =false;  
    }  
      
    public synchronized void watch(){  
        if(flag){ //消费者等待  
            try {  
                this.wait();  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  
        //开始消费  
        try {  
            Thread.sleep(200);  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
        System.out.println("消费了"+pic);  
        //消费完毕  
        //通知生产  
        this.notifyAll();  
        //消费停止  
        this.flag=true;  
    }  
}  

任务调度

  • Timer定时器类
  • TimerTask任务类
  • 通过java timer timertask:(spring的任务调度就是通过他们来实现的)
  • 在这种实现方式中,Timer类实现的是类似闹钟的功能,也就是定时或者每隔一段时间触发一次线程。其实Timer类本身就是一个线程,只是这个线程是用来实现调用其他线程的。而TimerTask类是一个抽象类,该类实现了Runnable接口,所以按照前面的介绍,该类具备多线程的能力。
  • 在这种实现方式中,通过继承TimerTask使该类获得了线程的能力,将需要的多线程执行的代码书写在run方法内部,然后通过Timer类启动线程的执行。
  • 在实际使用时,一个Timer可以启动任意多个TimerTask实现的线程,但是多个线程之间会存在阻塞。所以如果多个线程之间如果需要完全独立运行的话,最好还是一个Timer启动一个TimerTask实现。
import java.util.Date;  
import java.util.Timer;  
import java.util.TimerTask;  
/** 
    了解 
  Timer()  
  schedule(TimerTask task, Date time)  
  schedule(TimerTask task, Date firstTime, long period)  
  自学 quartz 
 * @author W.Sky 
 * 
 */  
public class TimeDemo01 {  
  
    public static void main(String[] args) {  
        Timer timer =new Timer();  
        timer.schedule(new TimerTask(){  
  
            @Override  
            public void run() {  
                System.out.println("so easy....");  
            }}, new Date(System.currentTimeMillis()+1000), 200);  
    }  
  
}  

Search

    Table of Contents