Java基础:多线程

多线程的创建方式(4种方法)

1. 继承Thread类

//main
    public static void main(String[] args) {
        //多线程的创建方式 1 : extends Thread
        MyThread1 myThread1 = new MyThread1();
        myThread1.start();
    }
//线程
public class MyThread1 extends Thread{
    @Override
    public void run() {
        System.out.println("this is thread extends Thread");
    }
}

2.实现Runnable接口

//main
    public static void main(String[] args) {
   		//创建多线程的方式 2 : 实现Runnable接口
        MyThread2 t = new MyThread2();
        Thread TtoRunnable1 = new Thread(t);
        Thread TtoRunnable2 = new Thread(t);
        TtoRunnable1.start();
        TtoRunnable2.start();
    }
public class MyThread2 implements Runnable {
    @Override
    public void run() {
        System.out.println("this is thread to implements Runnable");
    }
}
线程的优先级
    线程的优先级:
    1.MAX_PRIORITY = 10
    2.MIN_PRIORITY = 1
    3.NORM_PRIORITY = 5

    线程默认优先级为5
    优先级越大优先级越高,但是并不是优先级越大就越先执行
线程的状态

创建 、 等待、运行、阻塞、终止

两种实现方式的对比
实现Runnable 和 继承Thread 两种方式的对比

        实现Runnable的方式更好!
        因为,如果我们创建多个线程有一些共享的数据,则使用实现Runnable的方式
        否则可以使用继承Thread的方式

        联系:public class Thread implements Runnable

3. 实现Callable接口

如何理解实现Callable接口的方式创建多线程比实现Runnable接口创建多线程方式强大?
1. call()可以有返回值的。
2. call()可以抛出异常,被外面的操作捕获,获取异常的信息
3. Callable是支持泛型的
main
    public static void main(String[] args) {
        Thread8 t = new Thread8();
        FutureTask futureTask = new FutureTask(t);
        new Thread(futureTask).start();
        //对于返回指的获取
        try {
            Object sum = null;
            sum = futureTask.get();
            System.out.println(sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
class Thread8 implements Callable {

    @Override
    public Object call() throws Exception {
        System.out.println("this is thread to implements Callable");
        return 0;
    }
}

4.线程池

 好处:
 1.提高响应速度(减少了创建新线程的时间)
 2.降低资源消耗(重复利用线程池中线程,不需要每次都创建)
 3.便于线程管理
    corePoolSize:核心池的大小
    maximumPoolSize:最大线程数
    keepAliveTime:线程没有任务时最多保持多长时间后会终止
//main
        //1. 提供指定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);
        //2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象
        service.execute(new NumberThread());//适合适用于Runnable
        service.execute(new NumberThread1());//适合适用于Runnable
        service.submit(Callable callable);//适合使用于Callable
        //3.关闭连接池
        service.shutdown();

线程池的方法

/* 设置线程池的属性 */
        ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
        System.out.println(service.getClass());
        service1.setCorePoolSize(15);
        service1.setKeepAliveTime();

Thread类中常用方法

        //获取当前线程:Thread.currentThread();
        Thread thread = Thread.currentThread();
        //设置线程的名字:对象.setName(String name);
        Thread.currentThread().setName("设置当前线程的名称");
        myThread1.setName("设置myThread1的线程名");
        //获取线程名:对象.getNmae();
        String name1 = Thread.currentThread().getName();
        String name = myThread1.getName();
        //当前线程堵塞:this.sleep(int time)
        Thread.sleep(1000);
        //线程让出CPU,过一段时间在获取:yield()
        yield();
        //判断线程是否存活:对象.isAlive()
        boolean alive = Thread.currentThread().isAlive();

线程安全问题

买票重票、错票现象

//main
    public static void main(String[] args) {
        Thread1 t1 = new Thread1();
        Thread1 t2 = new Thread1();
        t1.start();
        t2.start();
    }
class Thread1 extends Thread{
    private static int ticket = 100;

    @Override
    public void run() {
        while(ticket > 0){
            System.out.println("卖出第" + (100 - ticket + 1) + "张票");
            ticket--;
            try {
                sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

线程安全问题的解决措施(3种方法)

1.同步代码块synchronized(类.class){}
public class MyThread1 extends Thread{
    private static int ticket = 100;

    @Override
    public void run() {
//        while(ticket > 0){ : 如果还这样写的话,ticket为0时仍然所有进程可以进入

        while (true) {
            synchronized (MyThread1.class) {
                if (ticket > 0) {
                    System.out.println("卖出第" + (100 - ticket + 1) + "张票");
                    ticket--;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    break;
                }
            }
        }
    }
}

public class MyThread2 implements Runnable {
    private int ticket = 100;
    @Override
    public void run() {
        while (true) {
            synchronized (MyThread2.class) {
                if (ticket > 0) {
                    System.out.println("卖出第" + (100 - ticket + 1) + "张票");
                    ticket--;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    break;
                }
            }
        }
    }

}

2.同步方法
public class MyThread3 extends Thread{
    private static int ticket = 100;

    @Override
    public void run() {
        while(true){
            show();
        }
    }
    /* 需要声明为static synchronized*/
    private static synchronized void show(){//此时同步监视器是Thread6.class
        if (ticket > 0) {
            System.out.println("卖出第" + (100 - ticket + 1) + "张票");
            ticket--;

            //sleep
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
3.lock锁
import java.util.concurrent.locks.ReentrantLock;

public class MyThread4 implements Runnable{
    private int ticket = 100;
    //1.实例化lock
    private ReentrantLock lock = new ReentrantLock(true);
    @Override
    public void run() {
        while(true){
            try{
                //2.调用锁定方法lock()
                lock.lock();

                if (ticket > 0) {
                    System.out.println("卖出第" + (100 - ticket + 1) + "张票");
                    ticket--;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                else{
                    break;
                }
            }finally {
                //3.解锁
                lock.unlock();
            }
        }
    }
}

线程通信问题


/**
 * 线程通信的例子:使用两个线程打印 1-100。线程1, 线程2 交替打印
 *
 * 涉及到的三个方法:
 * wait():一旦执行此方法,当前线程就进入阻塞状态,并释放同步监视器。
 * notify():一旦执行此方法,就会唤醒被wait的一个线程。如果有多个线程被wait,就唤醒优先级高的那个。
 * notifyAll():一旦执行此方法,就会唤醒所有被wait的线程。
 *
 * 说明:
 * 1.wait(),notify(),notifyAll()三个方法必须使用在同步代码块或同步方法中。
 * 2.wait(),notify(),notifyAll()三个方法的调用者必须是同步代码块或同步方法中的同步监视器。
 *    否则,会出现IllegalMonitorStateException异常
 * 3.wait(),notify(),notifyAll()三个方法是定义在java.lang.Object类中。
 *
 * 面试题:sleep() 和 wait()的异同?
 * 1.相同点:一旦执行方法,都可以使得当前的线程进入阻塞状态。
 * 2.不同点:1)两个方法声明的位置不同:Thread类中声明sleep() , Object类中声明wait()
 *          2)调用的要求不同:sleep()可以在任何需要的场景下调用。 wait()必须使用在同步代码块或同步方法中
 *          3)关于是否释放同步监视器:如果两个方法都使用在同步代码块或同步方法中,sleep()不会释放锁,wait()会释放锁。
 *
 */
class Number implements Runnable{
    private int number = 1;
    private Object obj = new Object();
    @Override
    public void run() {

        while(true){

            synchronized (obj) {

                obj.notify();

                if(number <= 100){

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

                    System.out.println(Thread.currentThread().getName() + ":" + number);
                    number++;
                    try {
                        //使得调用如下wait()方法的线程进入阻塞状态
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }else{
                    break;
                }
            }

        }

    }
}


public class day19_15 {
    public static void main(String[] args) {
        Number number = new Number();
        Thread t1 = new Thread(number);
        Thread t2 = new Thread(number);

        t1.setName("线程1");
        t2.setName("线程2");

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


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值