Java 多线程两种创建和使用方式、线程生命周期、Thread常用函数、线程同步(安全)

                            Thread类中的常用的方法

    1. start():启动当前线程;调用当前线程的run()
    1. run(): 通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法中
    1. currentThread():静态方法,返回执行当前代码的线程
    1. getName():获取当前线程的名字
    1. setName():设置当前线程的名字
    1. yield():释放当前cpu的执行权
    1. join():在线程a中调用线程b的join(),此时线程a就进入阻塞状态,直到线程b完全执行完以后,线程a才结束阻塞状态。
    1. stop():已过时。当执行此方法时,强制结束当前线程。
    1. sleep(long millitime):让当前线程“睡眠”指定的millitime毫秒。在指定的millitime毫秒时间内,当前线程是阻塞状态。
    1. isAlive():判断当前线程是否存活

线程的优先级:

  • MAX_PRIORITY:10

  • MIN _PRIORITY:1

  • NORM_PRIORITY:5 -->默认优先级

  • 2.如何获取和设置当前线程的优先级:

  • getPriority():获取线程的优先级

  • setPriority(int p):设置线程的优先级

  • 说明:高优先级的线程要抢占低优先级线程cpu的执行权。但是只是从概率上讲,高优先级的线程高概率的情况下被执行。并不意味着只当高优先级的线程执行完以后,低优先级的线程才执行。

线程通信:wait() / notify() / notifyAll() :此三个方法定义在Object类中的。

补充:线程的分类
一种是守护线程,一种是用户线程。

                            并行与并发的理解
并行:多个CPU同时执行多个任务。比如:多个人同时做不同的事。
并发:一个CPU(采用时间片)同时执行多个任务。比如:秒杀、多个人做同一件事

                                           线程生命周期在这里插入图片描述1.生命周期关注两个概念:状态、相应的方法
2.关注:状态a–>状态b:哪些方法执行了(回调方法)
某个方法主动调用:状态a–>状态b
3.阻塞:临时状态,不可以作为最终状态
死亡:最终状态。

方式一:继承Thread类的方式

    1. 创建一个继承于Thread类的子类
    1. 重写Thread类的run() --> 将此线程执行的操作声明在run()中
    1. 创建Thread类的子类的对象
    1. 通过此对象调用start():①启动当前线程 ② 调用当前线程的run()
/* 多线程创建,方式一:继承thread类
  1、创建一个继承于Thread类的子类
  2、重写Thread类的run()方法-->将此线程执行的操作声明在run()中
  3、创建Tread类的子类对象
  4、通过对象调用start()
  * */

class thread12 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i <100 ; i++) {
            if (i%2 == 0) {
             //   System.out.println(i);
                System.out.println(Thread.currentThread().getName()+":"+i);
            }
        }
    }
}


public class Thread1 {

    public static void main(String[] args) {
        System.out.println("方式一");
        thread12 t1= new thread12();    //创建Tread类的子类对象
        t1.start();                    //通过对象调用start();1 启动当前线程 2 调用当前线程的run() 子线程
       // t1.run();         //不能通过直接调用run()的方式启动线程

        /*
        * 一个对象只能调用start()一次,否则会抛出异常
        * 要想实现多线程,现需要创建多个对象
        * */

        //for循环仍在main线程执行
        for (int i = 0; i <100 ; i++) {
            if (i%2 == 0) {
                // System.out.println(i+"******main()**");
                System.out.println(Thread.currentThread().getName()+":"+i);
            }
        }
    }
}

方式二:实现Runnable接口的方式:

    1. 创建一个实现了Runnable接口的类
    1. 实现类去实现Runnable中的抽象方法:run()
    1. 创建实现类的对象
    1. 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
    1. 通过Thread类的对象调用start()
/**
 * 创建多线程的方式二:实现Runnable接口
 * 1. 创建一个实现了Runnable接口的类
 * 2. 实现类去实现Runnable中的抽象方法:run()
 * 3. 创建实现类的对象
 * 4. 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
 * 5. 通过Thread类的对象调用start()
 *
 *
 * 比较创建线程的两种方式。
 * 开发中:优先选择:实现Runnable接口的方式
 * 原因:1. 实现的方式没有类的单继承性的局限性
 *      2. 实现的方式更适合来处理多个线程有共享数据的情况。
 *
 * 联系:public class Thread implements Runnable
 * 相同点:两种方式都需要重写run(),将线程要执行的逻辑声明在run()中。
 */
//1. 创建一个实现了Runnable接口的类
class MThread implements Runnable{

    //2. 实现类去实现Runnable中的抽象方法:run()
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }

        }
    }
}


public class Thread{
    public static void main(String[] args) {
        //3. 创建实现类的对象
        MThread mThread = new MThread();
        //4. 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
        Thread t1 = new Thread(mThread);
        t1.setName("线程1");
        //5. 通过Thread类的对象调用start():① 启动线程 ②调用当前线程的run()-->调用了Runnable类型的target的run()
        t1.start();

        //再启动一个线程,遍历100以内的偶数
        Thread t2 = new Thread(mThread);
        t2.setName("线程2");
        t2.start();
    }
}

两种方式的对比:

  • 开发中:优先选择:实现Runnable接口的方式
  • 原因:1. 实现的方式没类的单继承性的局限性
               2. 实现的方式更适合来处理多个线程共享数据的情况。
  • 联系:public class Thread implements Runnable
  • 相同点:两种方式都需要重写run(),将线程要执行的逻辑声明在run()中。目前两种方式,要想启动线程,都是调用的Thread类中的start()。

注意点:
一:我们启动一个线程,必须调用start(),不能调用run()的方式启动线程。
二:如果再启动一个线程,必须重新创建一个Thread子类的对象,调用此对象的start().

                                           实现线程同步
实现线程同步(线程安全)的方式有使用synchronized 与 Lock,而使用synchronized 又分为同步代码块和同步方法
***** 1. 面试题:synchronized 与 Lock的异同?****

  • 相同:二者都可以解决线程安全问题
  • 不同:synchronized机制在执行完相应的同步代码以后,自动的释放同步监视器
  • Lock需要手动的启动同步(lock()),同时结束同步也需要手动的实现(unlock())
  • 2.优先使用顺序:
  • Lock --> 同步代码块(已经进入了方法体,分配了相应资源)–> 同步方法(在方法体之外)
    代码块实现继承Thread方式的线程同步
class Window2 extends Thread{


    private static int ticket = 100;

    private static Object obj = new Object();

    @Override
    public void run() {

        while(true){
            //正确的
//            synchronized (obj){
            synchronized (Window2.class){   //Class clazz = Window2.class,Window2.class只会加载一次
                //错误的方式:this代表着t1,t2,t3三个对象
//              synchronized (this){

                if(ticket > 0){

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(getName() + ":卖票,票号为:" + ticket);
                    ticket--;
                }else{
                    break;
                }
            }

        }

    }
}


public class jic {
    public static void main(String[] args) {
        Window2 t1 = new Window2();
        Window2 t2 = new Window2();
        Window2 t3 = new Window2();


        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();

    }
}

代码块实现Runnable接口的方式的线程同步

class Window1 implements Runnable{

    private int ticket = 100;
    Object obj = new Object();

    @Override
    public void run() {
        while(true){
            synchronized (obj){
                if(ticket > 0){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":卖票,票号为:" + ticket);
                    ticket--;
                }else{
                    break;
                }
            }
        }
    }
}


public class ticket {
    public static void main(String[] args) {
       Window1 w = new Window1();

        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }

}

同步方法实现继承Thread方式的线程同步

class Window2 extends Thread {


    private static int ticket = 100;

    private static Object obj = new Object();

    @Override
    public void run() {

        while (true) {
            show();
        }
    }

    public static synchronized void show() {//同步监视器:Window4.class
    // private synchronized void show(){ //同步监视器:t1,t2,t3。此种解决方式是错误的
        if (ticket > 0) {

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName() + ":卖票,票号为:" + ticket);
            ticket--;
        }
    }
}


public class jic {
    public static void main(String[] args) {
        Window2 t1 = new Window2();
        Window2 t2 = new Window2();
        Window2 t3 = new Window2();


        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();

    }
}

同步方法实现Runnable接口的方式的线程同步

class Window1 implements Runnable {

    private int ticket = 100;
    Object obj = new Object();

    @Override
    public void run() {
        while (true) {
            show();
        }
    }
    public synchronized void  show(){   //同步监视器:this
        if (ticket > 0) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":卖票,票号为:" + ticket);
            ticket--;
        }
    }
}
public class ticket {
    public static void main(String[] args) {
        Window1 w = new Window1();

        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}

lock锁实现线程同步

class Window implements Runnable{

    private int ticket = 100;
    //1.实例化ReentrantLock
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while(true){
            try{

                //2.调用锁定方法lock()
                lock.lock();

                if(ticket > 0){

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + ":售票,票号为:" + ticket);
                    ticket--;
                }else{
                    break;
                }
            }finally {
                //3.调用解锁方法:unlock()
                lock.unlock();
            }

        }
    }
}

public class LockTest {
    public static void main(String[] args) {
        Window w = new Window();

        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值