java线程基础

线程

1.程序、进程、线程

程序:简而言之就是我们的代码
进程:是一个程序运行起来动态的过程,会占用系统资源(内存,cpu)
线程:进程是一个动态的过程,进程可以产生线程

2.并发和并行

并发:同一时刻,多任务交替执行,单核cpu在多任务就是并发
并行:同一时刻,多任务同时执行。多核cpu实现并行。
并行也会出现并发情况

3.Thread

在这里插入图片描述

Thread类继承Runnable接口,实现Runnable中的run方法,run方法实际就是我们的业务逻辑代码

3.1 Thread中run方法

    /**
     * If this thread was constructed using a separate
     * <code>Runnable</code> run object, then that
     * <code>Runnable</code> object's <code>run</code> method is called;
     * otherwise, this method does nothing and returns.
     * <p>
     * Subclasses of <code>Thread</code> should override this method.
     *
     * @see     #start()
     * @see     #stop()
     * @see     #Thread(ThreadGroup, Runnable, String)
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

3.2 基础练习

//继承thread使用启动一个线程实现每1s输出一句话,第10句话结束
public class Test1 {
    public static void main(String[] args) {
        //继承thread使用
        //启动一个线程实现每1s输出一句话,第10句话结束
        new Talk().start();
    }

}
//创建一个Talk类继承Thread实现每隔一秒输出一句话
class Talk extends Thread{
    int index = 1;
    @Override
    public void run() {
        do {
            System.out.println("这是第" + index + "句话");
            //暂停一秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ++index;
        } while (index != 11);
    }
}

在这里插入图片描述

3.3 线程run和start的区别

如果run的话仅仅只是默认执行的是run方法并不会重新启动一个线程,而是在main主线程中串行执行
3.3.1 线程run
/**
 * @author luqianqi
 * @title: Test
 * @projectName thread
 * @description: TODO
 * @date 2021/5/99:59 上午
 */
public class Test1 {
    public static void main(String[] args) {
        //继承thread使用
        //启动一个线程实现每1s输出一句话,第10句话结束
        new Talk().run();
        //当主(main)线程启动一个子线程(talk)时,主不会阻塞等待子线程结束,而是会继续下进行
        for (int i = 1; i <= 10; i++) {
            System.out.print("main方法的线程名:"+Thread.currentThread().getName());
            System.out.println("主线程i = " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
//创建一个Talk类继承Thread实现每隔一秒输出一句话
class Talk extends Thread{
    int index = 1;
    @Override
    public void run() {
        do {
            System.out.println("这是第" + index + "句话");
            System.out.println("当前线程名:"+Thread.currentThread().getName());
            //暂停一秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ++index;
        } while (index != 11);
    }
}

在这里插入图片描述

3.3.2 线程start
线程start才是会真正的重新启动一个新线程,执行我们的业务代码,并且主线程不会阻塞继续往下执行
/**
 * @author luqianqi
 * @title: Test
 * @projectName thread
 * @description: TODO
 * @date 2021/5/99:59 上午
 */
public class Test1 {
    public static void main(String[] args) {
        //继承thread使用
        //启动一个线程实现每1s输出一句话,第10句话结束
        new Talk().start();
        //当主(main)线程启动一个子线程(talk)时,主不会阻塞等待子线程结束,而是会继续下进行
        for (int i = 1; i <= 10; i++) {
            System.out.print("main方法的线程名:"+Thread.currentThread().getName());
            System.out.println("主线程i = " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
//创建一个Talk类继承Thread实现每隔一秒输出一句话
class Talk extends Thread{
    int index = 1;
    @Override
    public void run() {
        do {
            System.out.println("这是第" + index + "句话");
            System.out.println("当前线程名:"+Thread.currentThread().getName());
            //暂停一秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ++index;
        } while (index != 11);
    }
}

在这里插入图片描述

3.3.3 为什么start能运行我们写在run中的业务代码
start()方法会调用start0,native方法是jvm虚拟机调用的方法,start0以后不会立即执行而是将线程变成可执行状态,由cpu执行统一调度
  public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

    private native void start0();//native方法是jvm虚拟机调用的方法,start0以后不会立即执行而是将线程变成可执行状态,由cpu执行统一调度

3.4 jconsole可以查看主线使用情况

4.Runnable

4.1 java类不能继承多父类
java子类不能继承多父类,所以如果一个类继承类一个父类,想要继承Thread类是不行的,所以需要实现Runnable接口来实现线程run
/**
 * @author luqianqi
 * @title: Test
 * @projectName thread
 * @description: TODO
 * @date 2021/5/911:05 上午
 */
public class Test {
    public static void main(String[] args) {
        Thread thread = new Thread(new Pelple());
        thread.start();
    }
}
class Pelple implements Runnable{
    int index = 1;
    @Override
    public void run() {
        while (true){
            System.out.println("我就是爱笑xixi"+(++index)+Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
4.2 代理模式
/**
 * 代理模式
 */
class ThreadProxy implements Runnable{
    private Runnable target = null;
    @Override
    public void run() {
        if (target != null){
            target.run();
        }
    }
    public ThreadProxy(Runnable target){
         this.target = target;
    }
    public void start(){
        start0();//真正实现多线程的方法
    }

    private void start0() {
        run();
    }
}

5.多线程

5.1 基础多线程练习

使用实现Runnable的方式创建两个线程,一个循环10次一个循环20次
/**
 * @author luqianqi
 * @title: Test2
 * @projectName thread
 * @description: TODO
 * @date 2021/5/911:32 上午
 */
public class Test2 {
    public static void main(String[] args) {
        QiQi qiQi = new QiQi();
        XiXi xiXi = new XiXi();
        Thread qiqi = new Thread(qiQi);
        Thread xixi = new Thread(xiXi);
        qiqi.start();
        xixi.start();
        System.out.println("main线程接收线程名:"+Thread.currentThread().getName());
    }
}
class People {

}
class QiQi extends People implements Runnable{

    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.println("我是QiQi"+i+"当前线程名:"+Thread.currentThread().getName());
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class XiXi extends People implements Runnable{

    @Override
    public void run() {
        for (int i = 1; i <= 20; i++) {
            System.out.println("我是XiXi"+i+"当前线程名:"+Thread.currentThread().getName());
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

在这里插入图片描述

5.2 多线程售票实例

/**
 * @author luqianqi
 * @title: Ticket
 * @projectName thread
 * @description: TODO
 * @date 2021/5/911:55 上午
 */
public class Ticket {
    public static void main(String[] args) {
        Ticket2 ticket2 = new Ticket2();
        new Thread(ticket2).start();
        new Thread(ticket2).start();
        new Thread(ticket2).start();
    }
}

class Ticket1 extends Thread{
    private static int num  = 100;
    @Override
    public void run() {
        do {
            System.out.println("ticket1售出一张票当前线程:"+Thread.currentThread().getName()+"剩余票:"+num);
            --num;
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }while (num >= 0);
        System.out.println("售票结束");
    }
}
class Ticket2 implements Runnable{
    private  int num  = 100;
    @Override
    public void run() {
       while (true){
           if (num <= 0){
               System.out.println("售票结束");
               break;
           }
           try {
               Thread.sleep(10);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           System.out.println("ticket1售出一张票当前线程:"+Thread.currentThread().getName()+"剩余票:"+(--num));
       }
    }
}

5.3 线程终止

/**
 * @author luqianqi
 * @title: Test2
 * @projectName thread
 * @description: TODO
 * @date 2021/5/91:11 下午
 */
public class Test2 {
    public static void main(String[] args) throws InterruptedException {
        ThreadExit threadExit = new ThreadExit();
        threadExit.start();
        Thread.sleep(1000);
        threadExit.setLoop(false);//在主线程控制子线程结束
    }
}
class ThreadExit extends Thread{
    private boolean loop  = true; //标志位
   private int index = 0;
    @Override
    public void run() {
        while (loop){
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程循环:"+(++index));
        }
    }

    public boolean isLoop() {
        return loop;
    }

    public void setLoop(boolean loop) {
        this.loop = loop;
    }
}

6.线程常用的方法

6.1 (interrupt、yield、join)

/**
 * @author luqianqi
 * @title: ThreadMethod
 * @projectName thread
 * @description: TODO
 * @date 2021/5/91:23 下午
 */
public class ThreadMethod01 {
    public static void main(String[] args) throws InterruptedException {
        T t = new T();
        t.setName("lqq");//设置线程名
        t.setPriority(Thread.MIN_PRIORITY);//线程优先级
        t.start();
        for (int i = 0; i < 5; i++) {
            Thread.sleep(1000);
            System.out.println("主线程----");
        }
        System.out.println("阻断子线程:"+t.getName()+"休眠");
        t.interrupt();//阻断线程休眠
    }
}

class T extends Thread{
    @Override
    public void run() {
        while (true){
            for (int i = 0; i < 100; i++) {
                System.out.println(Thread.currentThread().getName()+"干饭");
            }
            try {
                System.out.println(Thread.currentThread().getName()+"干累了休息一会");
                Thread.sleep(20000);
            }catch (InterruptedException e){
                System.out.println(Thread.currentThread().getName()+"发生异常");
            }
        }

    }
}
/**
 * @author luqianqi
 * @title: ThreadMethod2
 * @projectName thread
 * @description: TODO
 * @date 2021/5/91:39 下午
 */
public class ThreadMethod2 {
    public static void main(String[] args) throws InterruptedException {
        T1 t1 = new T1();
        t1.setName("lqq");
        t1.start();
        for (int i = 0; i < 10; i++) {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName()+i);
            if (i == 5){
                System.out.println("插队开始");
                //t1.join();//插队
                t1.yield();//礼让不一定好使
                System.out.println("插队结束----继续执行main");
            }
        }

    }
}
class T1 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"i = " + i);
        }
    }
}

6.2 守护线程

public class ThreadMethod3 {
    public static void main(String[] args) throws InterruptedException {
        MyDaemonThread myDaemonThread = new MyDaemonThread();
        myDaemonThread.setDaemon(true);//设置守护线程
        myDaemonThread.start();
        for (int i = 0; i < 10; i++) {
            System.out.println("你们在谈恋爱-----");
            Thread.sleep(1000);
        }
    }
}
class MyDaemonThread extends Thread{
    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("lqq在努力地搬砖------");
        }
    }
}

在这里插入图片描述

6.3 线程同步机制Synchronized

线程同步:在多线程中一些敏感资源访问时,我们需要确保任一时间段,最多只有一个线程进行访问,以确保数据的完整性
class Ticket3 implements Runnable{
    private  int num  = 100;
    private boolean loop = false;
    @Override
    public  void run() {
        while (true){
            extracted();
            if (loop){
                break;
            }
        }
    }
	
    public synchronized void extracted() {
        if (num <= 0){
            System.out.println("售票结束");
            loop = true;
            return;
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("ticket1售出一张票当前线程:"+Thread.currentThread().getName()+"剩余票:"+(--num));
    }
}

在这里插入图片描述

7. 锁

7.1 互斥锁

Synchronized修饰某个对象,此对象只能被一个线程进行执行,非公平锁,效率很低
同步方法没有使用static修饰默认锁对象是this
如果同步方法为静态方法则锁的对象是当前类
锁的对像一定要是同一个对象:就好比三个人要去上厕所,只有一个厕所,只能一个人进厕所门,我们要保证每个人都是从这一个门进去的!!!
class Ticket3 implements Runnable{
    private  int num  = 100;
    private boolean loop = false;
    Object object = new Object();
    @Override
    public  void run() {
        while (true){
            extracted();
            if (loop){
                break;
            }
        }
    }
    //synchronized 修饰同步方法静态的锁当前类而不是当前对象
    public static  void m1(){
        synchronized (Ticket3.class){
            System.out.println("hahahha");
        }
    }
        //同步方法(非静态)现在锁的的是当前对象this
    public  void extracted() {
        synchronized (object){
            if (num <= 0){
                System.out.println("售票结束");
                loop = true;
                return;
            }
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("ticket1售出一张票当前线程:"+Thread.currentThread().getName()+"剩余票:"+(--num));
        }

    }
}

7.2 死锁

多线程互相占用对方的资源,造成了线程都无法进行的情况
/**
 * @author luqianqi
 * @title: DeadLock
 * @projectName thread
 * @description: TODO
 * @date 2021/5/93:01 下午
 */
public class DeadLock {
    public static void main(String[] args) {
        new DeadLockDemo(false).start();
        new DeadLockDemo(true).start();
    }
}
class DeadLockDemo extends Thread{
    static Object o1 = new Object();
    static Object o2 = new Object();
    boolean flag;
    public DeadLockDemo(boolean flag){
        this.flag = flag;
    }

    @Override
    public void run() {
        //如果flag为true 线程A会持有o1对象锁,尝试获得o2对象锁,如果拿不到o2就会blocked
        //如果flag为false 线程B会持有o2对象锁,尝试获得o1对象锁,如果拿不到o1就会blocked

        if (flag){
            synchronized (o1){//同步代码
                System.out.println(Thread.currentThread().getName()+"进入1");
                synchronized (o2){
                    System.out.println(Thread.currentThread().getName()+"进2");
                }
            }
        }else {
            synchronized (o2){//同步代码
                System.out.println(Thread.currentThread().getName()+"进入3");
                synchronized (o1){
                    System.out.println(Thread.currentThread().getName()+"进4 ");
                }
            }
        }

    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值