线程:

知识点:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

Thread.sleep()    线程睡眠 ,需要try,但是不释放锁

this.wait()  线程进入等待状态(需要notify来唤醒该线程),释放锁 ,this.notify()  换醒线程,利用他可以做线程之间的切换转换    注意:wait需要在同步方法中使用

Thread.yield()     让出本次CPU执行时间片,通常用来 协程 使用

线程.join()  等待线程结束

基本操作

public class Demo {
    public static void main(String[] args) {
        //使用类的继承方法
        MyThread1 mt = new MyThread1();
        mt.start(); //表示线程处于就绪状态,等待cpu的调用

        //使用接口的方式,推荐使用
        //将Mythread2这个任务放到Thread这个线程中完成
        Thread t = new Thread(new Mythread2());
        t.start();
    }
}
class MyThread1 extends Thread{
    public void run(){
        for (int i = 0; i <100 ; i++) {
            System.out.println(i+"->"+Thread.currentThread().getName());
        }
    }
}

class Mythread2 implements Runnable{
    public void run() {
        for (int i = 0; i <100 ; i++) {
            System.out.println(i+"->"+Thread.currentThread().getName());
        }
    }
}

  

线程终断

方式1:

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

        Thread t = new Thread(new Mythread2());
        t.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t.interrupt(); //表示给当前的线程打上中断标记,不能真正的中断线程;
    }
}
class Mythread2 implements Runnable{
    public void run() {
        for (int i = 0; i <10 ; i++) {
            if(Thread.interrupted()){//如果线程存在中断标记;
                break;
                //return;
            }
            try {
                sleep(500);
            } catch (InterruptedException e) {//任何线程中断中断当前线程;抛出异常,当前线程的中断状态被清除;
                e.printStackTrace();
                Thread.currentThread().interrupt();//给线程在打上中断标记
            }
            System.out.println(i+"->"+Thread.currentThread().getName());
        }
        System.out.println("线程已经终止");
    }
}

方式2:使用自定义的标记(推荐)

public class Demo {
    public static void main(String[] args) {
        Mythread2 th = new Mythread2();
        Thread t = new Thread(th);
        t.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        th.flag=false; //自定义中断标记
    }
}
class Mythread2 implements Runnable{
    public boolean flag = true;
    public void run() {
        for (int i = 0; i <10 ; i++) {
            if(flag==false){
                //return;
                break;
            }
            try {
                sleep(500);
            } catch (InterruptedException e) {//任何线程中断中断当前线程;抛出异常,当前线程的中断状态被清除;
                e.printStackTrace();
            }
            System.out.println(i+"->"+Thread.currentThread().getName());
        }
        System.out.println("线程已经终止");
    }
}

  

守护线程

线程:分为用户线程和守护线程;

JVM 只关心用户线程,默认所有的设置的线程都是用户线程,当用户线程执行完毕之后,JVM就会退出,如果把一个线程设置为守护线程,那么JVM不在关心这个线程是否执行完毕了

public class Demo {
    public static void main(String[] args) {
        Mythread2 th = new Mythread2();
        Thread t = new Thread(th);
        t.setDaemon(true);//把线程设置为守护线程
        t.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("主线程退出;");
    }
}
class Mythread2 implements Runnable{
    public void run() {
        for (int i = 0; i <10 ; i++) {
            try {
                sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(i+"->"+Thread.currentThread().getName());
        }
    }
}

 

线程同步 

方式一: 使用 synchronized 将数据包裹起来; (同步代码块)

public class Demo {
    public static void main(String[] args) {
        Mythread2 th = new Mythread2();
        for (int i = 0; i <2 ; i++) {
            new Thread(th).start();
        }
    }
}
class Mythread2 implements Runnable{
    public int ticket=10;
    private Object obj = new Object();
    public void run() {
            while(true){
                synchronized (obj){  //直接写synchronized(this)也可以,没有实际意义
                if(ticket>0){
                    ticket--;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("还有"+ticket+"张票"+"->"+Thread.currentThread().getName());
                }else{
                    break;
                }
            }
        }
    }
}

  

方法二:使用同步方法:同步的对象是当前的对象(this)

注意事项:如果在同步方法内部又调用了该对象的另一个同步方法,就会发生死锁,同步方法本质  synchronized(this);

public class Demo {
    public static void main(String[] args) {
        Mythread2 th = new Mythread2();
        for (int i = 0; i < 2; i++) {
            new Thread(th).start();
        }
    }
}

class Mythread2 implements Runnable {
    public int ticket = 10;
    private Boolean flag=true;
    public void run() {
        while (flag) {
            method();
        }
    }
  //同步方法
    private synchronized void method() {
       ticket--;
       if (ticket>=0){
           try {
               Thread.sleep(100);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           System.out.println("还有" + ticket + "张票" + "->" + Thread.currentThread().getName());
       }else {
           flag=false;
       }
    }
}

 

方法三:使用lock()  更加灵活

import java.util.concurrent.locks.ReentrantLock;

public class Demo {
    public static void main(String[] args) {
        Mythread2 th = new Mythread2();

        for (int i = 0; i < 2; i++) {
            new Thread(th).start();
        }
    }
}
class Mythread2 implements Runnable {
    public int ticket = 10;
    private Boolean flag=true;
    ReentrantLock lock = new ReentrantLock();
    public void run() {
        while (flag) {
            lock.lock();
            try{
                ticket--;
                if (ticket>=0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("还有" + ticket + "张票" + "->" + Thread.currentThread().getName());
                }else {
                    flag=false;
                }
            }finally {//避免死锁
                lock.unlock();
            }
        }
    }
}

  

生产者消费者模型

public class Demo {
    public static void main(String[] args) {
        Food food = new Food();
        new Thread(new Chef(food)).start();
        new Thread(new Customer(food)).start();

    }
}
class Chef implements Runnable{
    private Food food;
    public Chef(Food food){
        this.food = food;
    }
    public void setfood(){
        this.food.setfood();
    }
    @Override
    public void run() {
        setfood();
    }
}
class Customer implements Runnable{
    private Food food;
    public Customer(Food food){
        this.food = food;
    }
    public void getfood(){
        this.food.getfood();
    }

    @Override
    public void run() {
        getfood();
    }
}

class Food{
    private String name;
    private Boolean flag = true;

    public synchronized void setfood(){
        for (int i = 0; i <10 ; i++) {
            if (!flag){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("包子"+i+"制作完毕");
            this.name = "包子"+i;
            flag = false;
            this.notify();
        }
    }
    public synchronized void getfood(){
        for (int i = 0; i < 10; i++) {
            if (flag){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(this.name+"已经吃完");
            flag=true;
            this.notify();
        }
    }
}

线程池

 

public class Demo {
    public static void main(String[] args) {
        //创建一个单线程的线程池
        //ExecutorService es1 =  Executors.newSingleThreadExecutor();
        //es1.execute(new Test()); //完成任务之后,线程不会结束;
        //es1.execute(new Test());
        //es1.shutdown();  //结束线程池;

        //创建一个固定的大小的线程池
        //ExecutorService es2 =  Executors.newFixedThreadPool(4);
        //es2.execute(new Test()); //完成任务之后,线程不会结束;
        //es2.execute(new Test());

        //线程池的大小依赖操作系统;并且操作系统会自动对不工作的线程进行回收
        //ExecutorService es3 =  Executors.newCachedThreadPool();

        //任务延迟3秒后执行
        ScheduledExecutorService es4 = Executors.newScheduledThreadPool(3);
        es4.schedule(new Test(),3000, TimeUnit.MILLISECONDS);
    }
}
class Test implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(i+"->"+Thread.currentThread().getName());
        }
    }
}

 

  

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄