创立线程的办法

  • 继承Thread类
  • 继承Thread类,重写run办法,通过线程类实例.start()办法开启线程。
public class TestThread1 extends Thread{    @override    public void run(){        System.out.println("线程run办法!");    }        public static void main(String){        new TestThread1().start();    }}
  • 实现Runnable接口

    • 实现Runnable接口,重写run办法,通过new Thread(线程类实例).start()开启线程
    • 举荐应用该形式,防止java的单继承局限性
public class TestThread2 implements Runnable{    @Override    public void run() {        System.out.println("线程run办法!");    }        public static void main(String[] args) {        new Thread(new TestThread2()).start();    }}
  • 实现Callable接口
  • 实现Callable接口,重写call办法,call办法有返回值

    • 启动形式:

      • 创立执行服务
      • 提交执行
      • 获取后果
      • 敞开服务
public class TestThread2 implements Callable{    @Override    public Boolean call() {        System.out.println("线程call办法!");        return true;    }        public static void main(String[] args) throws InterruptedException, ExecutionException {                TestThread2 t1 = new TestThread2();        TestThread2 t2 = new TestThread2();        TestThread2 t3 = new TestThread2();        //创立执行服务        ExecutorService ser = Executors.newFixedThreadPool(3);        //提交执行        Future<Boolean> r1 = ser.submit(t1);        Future<Boolean> r2 = ser.submit(t2);        Future<Boolean> r3 = ser.submit(t3);        //获取后果        boolean rs1 = r1.get();        boolean rs2 = r2.get();        boolean rs3 = r3.get();        //敞开服务        ser.shutdownNow();    }

线程同步

  • 多个线程同时操作同一资源,线程不平安,变量值错乱
  • 加锁
  • 队列+锁(synchronized)
  • synchronized默认锁this,能够显示指定锁的对象来批改

1. synchronized润饰办法,线程平安办法

public class TestThreadSafe {    public static void main(String[] args) {        BuyTicket bt1 = new BuyTicket();        Thread thread1 = new Thread(bt1,"张三");        Thread thread2 = new Thread(bt1,"李四");        Thread thread3 = new Thread(bt1,"黄牛");        thread1.start();        thread2.start();        thread3.start();    }}class BuyTicket implements Runnable{    private int ticketNumber = 10;    private boolean flag = true;    @Override    public void run() {        while(flag) {            try {                buy();            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }    public synchronized void buy() throws InterruptedException {        //买票        if(ticketNumber <= 0){            System.out.println("票卖完了!");            flag = false;            return;        }        Thread.sleep(100);        //Thread.yield();        System.out.println(Thread.currentThread().getName() + "买到了一张票,还剩下"+(--ticketNumber) + "张票!");    }}

2. synchronized润饰代码块,线程平安代码块

public class TestThreadSafe {    public static void main(String[] args) {        BuyTicket bt1 = new BuyTicket();        Thread thread1 = new Thread(bt1,"张三");        Thread thread2 = new Thread(bt1,"李四");        Thread thread3 = new Thread(bt1,"黄牛");        thread1.start();        thread2.start();        thread3.start();    }}class BuyTicket implements Runnable{    private int ticketNumber = 10;    private boolean flag = true;    @Override    public void run() {        while(flag) {            System.out.println(Thread.currentThread().getName() + "筹备买票" + flag);            try {                buy();            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }    public void buy() throws InterruptedException {        synchronized(this){            //买票            if(ticketNumber <= 0){                flag = false;                System.out.println("票卖完了!");                return;            }            Thread.sleep(100);            //Thread.yield();            System.out.println(Thread.currentThread().getName() + "买到了一张票,还剩下"+(--ticketNumber) + "张票!");        }    }}

3. 应用可反复锁ReentrantLock

import java.util.concurrent.locks.ReentrantLock;public class TestLock {    public static void main(String[] args) {        BuyTicket bt1 = new BuyTicket();        Thread thread1 = new Thread(bt1,"张三");        Thread thread2 = new Thread(bt1,"李四");        Thread thread3 = new Thread(bt1,"黄牛");        thread1.start();        thread2.start();        thread3.start();    }}class BuyTicket implements Runnable{    private int ticketNumber = 1000;    private boolean flag = true;  //定义可反复锁    private    final ReentrantLock lock = new ReentrantLock();        @Override    public void run() {        while(flag) {            try {                buy();            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }    public void buy() throws InterruptedException {            lock.lock();            //买票            if(ticketNumber <= 0){                System.out.println("票卖完了!");                flag = false;            }else {                Thread.sleep(100);                //Thread.yield();                System.out.println(Thread.currentThread().getName() + "买到了一张票,还剩下"+(--ticketNumber) + "张票!");            }            lock.unlock();    }}
  • 死锁

    • 两个以上的对象锁,每个线程相互占有对方须要的资源。造成死锁。

线程状态

  • 新生状态(new)
  • 就绪状态(start)
  • 阻塞状态(sleep、wait、同步锁定)
  • 运行状态
  • 死亡状态 线程对象进入死亡状态后,将不能再次调用start()办法再次启动

线程(Thread类)办法

  • setPriority(int newPriority) 更改线程优先级 newPriority从1到10
  • static void sleep(long millis) 使以后正在执行的线程休眠指定毫秒,不会开释线程锁对象
  • void join() 线程合并,期待该线程终止
  • static void yield() 暂停以后正在执行的线程,执行其它线程
  • void interrupt() 中断线程
  • boolean isAlive() 该线程是否沉闷

守护线程

  • setDaemon(true) : 设置为守护线程
  • 线程分为用户线程和守护线程
  • JVM虚拟机确保用户线程执行结束
  • JVM虚拟机不必期待守护线程执行结束
         eg:后盾记录操作日志,监控内存,垃圾回收期待

最初

感激你看到这里,看完有什么的不懂的能够在评论区问我,感觉文章对你有帮忙的话记得给我点个赞,每天都会分享java相干技术文章或行业资讯,欢送大家关注和转发文章!