Java高级知识复习----多线程的四种实现。

本文详细介绍了Java多线程的创建方式(继承Thread与实现Runnable),展示了如何通过继承Runnable接口避免单继承限制,以及线程安全问题的解决方案,包括同步代码块、同步方法和使用Lock锁。还涉及了Callable接口的使用,以及如何利用线程池提高效率。
摘要由CSDN通过智能技术生成

目录

1、Thread

1.Thread建立两个分线程分别输出十以内的奇数和十以内的偶数

2.常见Thread方法测试

2.通过继承Runnable接口实现多线程。

3.两种线程 的比较:

4.线程的安全问题

1.同步代码块

2.同步方法

3.1单例模式饿汉式同步方法

3.2同步代码块

4.死锁的演示:

5.解决线程安全问题的方式3---lock锁

5.线程通信问题

1.两个线程交替打印1-100。

2.线程通信经典问题

6.Callable

7.线程池


1、Thread

package top.oneluckyguy.java;

/**
 * @author Liu Qingfeng
 * @create 2020-12-12----16:47
 * 多线程的创建,方式一:继承于Thread
 * 1.创建一个继承自Thread的类
 * 2.重写Thread类的run() ,将此线程执行的操作声明在run()中
 * 3.创建Thread类的子类对象
 * 4.通过此对象调用start()
 * eg:遍历100以内所有的偶数。
 */
public class ThreadTest {
    public static void main(String[] args) {
//        3.创建Thread类的子类对象
        MyThread myThread = new MyThread();
//        4.通过此对象调用start()
        myThread.start();
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0){
                System.out.println(i + "********main******");
            }
        }
    }
}
//1.创建一个继承自Thread的类
class MyThread extends Thread{
//2.重写Thread类的run() ,将此线程执行的操作声明在run()中
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0){
                System.out.println(i);
            }
        }
    }
}

输出结果:部分截图,体现了多线程

1.Thread建立两个分线程分别输出十以内的奇数和十以内的偶数

package top.oneluckyguy.java;

/**
 * @author Liu Qingfeng
 * @create 2020-12-13----1:01
 */
public class MyThread{
    public static void main(String[] args) {
        MyThread1 myThread1 = new MyThread1();
        MyThread2 myThread2 = new MyThread2();
        myThread1.start();
        myThread2.start();
    }

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

结果:

h

2.常见Thread方法测试

package top.oneluckyguy.thread;

/**
 * @author Liu Qingfeng
 * @create 2020-12-13----1:56
 * 测试Thread中的常用方法:
 * 1.start():启动当前线程:调用当前线程的run()
 * 2.run():通常需要重写Thread类中的此方法,讲创建的线程要执行的操作声明在此方法中
 * 3.currentThread():静态方法,返回执行当前代码的线程
 * 4.getName():获取当前线程的名字
 * 5.setName():设置当前线程的名字
 * 6.yield():释放当前cpu的执行权
 * 7.join():在线程a中调用线程b的join(),此时线程a就处于阻塞状态,直到线程b执行完,线程a才结束阻塞状态。
 * 8.stop():已过时,当执行此方法时候,强制结束当前进程。
 * 9.sleep(long millitime):让当前线程睡眠,指定的millitime毫秒,在指定的millitime毫秒时间内线程是阻塞状态
 * 10.isAlive():判断当前线程是否还存活
 */
public class ThreadMethodTest {
    public static void main(String[] args) {
        ThreadText threadText = new ThreadText();
//        给threadText线程命名
        threadText.setName("线程一");
        threadText.start();
//        给主线程命名
        Thread.currentThread().setName("主线程");
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){

                System.out.println(Thread.currentThread().getName() + ": " + i);
            }

            if (i  == 20){
                try {
                    threadText.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
        System.out.println(threadText.isAlive());
    }
}
class ThreadText extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){
                try {
                    sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
            if (i % 20 == 0){
                yield();
            }
        }
    }
}

2.通过继承Runnable接口实现多线程。

package top.oneluckyguy.thread;

/**
 * @author Liu Qingfeng
 * @create 2020-12-13----19:41
 * 创建多线程的方式二:实现Runnable接口
 * 1.创建一个实现了Runnable接口的类。
 * 2.实现类去实现Runnable中的抽象方法:run()
 * 3.创建实现类的对象
 * 4.将此对象作为参数传到Thread类的构造器中,创建Thread类的对象
 * 5.通过Thread类的对象调用start()
 */
public class RunnableTest {
    public static void main(String[] args) {
        Mthread mthread = new Mthread();
        Thread thread = new Thread(mthread);
        thread.start();
//        再启动一个线程遍历100以内的偶数
        Thread thread1 = new Thread(mthread);
        thread1.start();
    }
}
class Mthread implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i % 2 == 0){
                System.out.println(i);
            }
        }
    }
}

3.两种线程 的比较:

开发中优先选择实现Runnable接口的方式

原因:1.实现的方式没有类的单继承性的局限性。

          2.实现的方式更适合处理多个线程有共享数据的情况

联系:

以下两个代码只是为了比较实现Runnable接口和继承Thread类的不同,线程安全性尚未考虑。后边完善。

package top.oneluckyguy.thread;

/**
 * @author Liu Qingfeng
 * @create 2020-12-13----13:34
 * eg:创建三个窗口卖票
 */
public class WindowTest {
    public static void main(String[] args) {
        Window window1 = new Window();
        Window window2 = new Window();
        Window window3 = new Window();
        window1.setName("窗口一");
        window2.setName("窗口二");
        window3.setName("窗口三");
        window1.start();
        window2.start();
        window3.start();
    }
}
class Window extends Thread{
    //要用静态变量才能够实现只有100个线程而不是三百个
    private static int ticket = 100;

    @Override
    public void run() {
        while (true){
            if(ticket > 0){
                System.out.println(getName() + ":卖票,票号为:" + ticket);
                ticket--;
            }else{
                break;
            }
        }
    }
}

 

package top.oneluckyguy.thread;

import javax.sound.midi.Soundbank;

/**
 * @author Liu Qingfeng
 * @create 2020-12-13----19:55
 */
public class WindowTest1 {
    public static void main(String[] args) {
        Window1 window1 = new Window1();
        Thread thread = new Thread(window1);
        Thread thread1 = new Thread(window1);
        Thread thread2 = new Thread(window1);
        thread.setName("窗口一");
        thread1.setName("窗口二");
        thread2.setName("窗口三");
        thread.start();
        thread1.start();
        thread2.start();
    }
}
class Window1 implements Runnable{
//不用声明static的变量就可以实现三个线程总票数是100个
    private int ticket = 100;
    @Override
    public void run() {
        while (true){
            if(ticket > 0){
                System.out.println(Thread.currentThread().getName() + ":卖票,票号为:" + ticket);
                ticket--;
            }else{
                break;
            }
        }
    }
}

4.线程的安全问题

1.同步代码块

package top.oneluckyguy.thread;

import javax.sound.midi.Soundbank;

/**
 * @author Liu Qingfeng
 * @create 2020-12-13----19:55
 * 例子 :创建三个窗口卖票,总数为100张,使用实现Runnable接口的方式
 *
 * 1.问题:买票戳成出现了重票,错票--->出现了线程安全问题
 * 2.问题出现的原因:当某个线程操作车票的过程中,尚未操作完成时,其他线程参与进来,也操作车票
 * 3.如何解决:当一个线程a再操作ticket的时候,其他线程不能参与进来直到a线程操作完ticket时,其他线程才可以操作ticket,这种情况即使线程a出现了阻塞也不能改变。
 * 4.再Java中,我们通过同步机制来解决线程安全问题。
 * 方式一:同步代码块
 *         synchronized(同步监视器){
 *             //需要被同步的代码
 *         }
 *         synchronized不能包多了,也不能包少了。不同于try——catch
 *         try——catch包多了没啥。
 * 说明: 1.操作共享数据的代码就是需要被同步的代码
 *       2.共享数据:多个线程共同操作,的变量
 *       3.同步监视器:俗称锁,任何一个类的对象都可以成为锁
 *       要求:多个线程必须要公用同一把锁
 *       补充:使用实现Runnable接口可以考虑用this作为锁,在继承Thread类的多线程中要慎用this作为锁,因为锁要一致
 *
 * 方式二:同步方法
 * 如果操作共享数据的代码完整的声明在一个方法中,我们不妨将此方法声明为同步的。
 *
 * 5.同步的方式,解决了线程安全问题
 *
 */
public class WindowTest1 {
    public static void main(String[] args) {
        Window1 window1 = new Window1();
        Thread thread = new Thread(window1);
        Thread thread1 = new Thread(window1);
        Thread thread2 = new Thread(window1);
        thread.setName("窗口一");
        thread1.setName("窗口二");
        thread2.setName("窗口三");
        thread.start();
        thread1.start();
        thread2.start();
    }
}
class Window1 implements Runnable{
    private int ticket = 100;
    Object object = new Object();
    @Override
    public void run() {
        while (true){
            //这里可以直接用this而不用声明Object对象,但是继承Thread类的时候就不能用this了。
            synchronized (this){
                if(ticket > 0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if(ticket > 0){
                    System.out.println(Thread.currentThread().getName() + ":卖票,票号为:" + ticket);
                    ticket--;
                }else{
                    break;
                }
            }
        }
    }
}

2.同步方法

package top.oneluckyguy.thread;

/**
 * @author Liu Qingfeng
 * @create 2020-12-13----13:34
 * eg:创建三个窗口卖票
 * 同步方法
 */
public class WindowTest {
    public static void main(String[] args) {
        Window window1 = new Window();
        Window window2 = new Window();
        Window window3 = new Window();
        window1.setName("窗口一");
        window2.setName("窗口二");
        window3.setName("窗口三");
        window1.start();
        window2.start();
        window3.start();
    }
}
class Window extends Thread{
    //要用静态变量才能够实现只有100个线程而不是三百个
    private static int ticket = 100;
    //这里的object 也要static才行
    private static Object object = new Object();
    @Override
    public void run() {
        while (true){
            show();
            if (ticket == 0){
                break;
            }
        }

    }
    public synchronized void  show(){   //默认this  如果继承Thread中想用方法就要把这个函数声明称静态的。。getName()也要声明称Thread.currentThread.getName()
        if(ticket > 0){
            System.out.println(getName() + ":卖票,票号为:" + ticket);
            ticket--;
        }
    }
}

3.1单例模式饿汉式同步方法

/**
 * @author Liu Qingfeng
 * @create 2020-12-13----22:02
 */
public class BankTest {
    public static void main(String[] args) {

    }
}
class Bank{

    private void Bank(){

    }
    private static Bank instance = null;
    public static synchronized Bank getInstance(Bank bank){
        if(instance == null){
            instance = new Bank();
        }
        return instance;
    }

}

3.2同步代码块

package top.oneluckyguy.bank;

/**
 * @author Liu Qingfeng
 * @create 2020-12-13----22:02
 */
public class BankTest {
    public static void main(String[] args) {

    }
}
class Bank{

    private void Bank(){

    }
    private static Bank instance = null;
    public static  Bank getInstance(Bank bank){
        if (instance == null){
            synchronized (Bank.class){
                if(instance == null) {
                    instance = new Bank();
                }
            }
        }
        return instance;
    }

}

4.死锁的演示:

package top.oneluckyguy.thread;

/**
 * @author Liu Qingfeng
 * @create 2020-12-13----22:46
 * 演示线程的死锁问题
 */
public class DeathLockTest {
    public static void main(String[] args) {
        StringBuffer stringBuffer = new StringBuffer();
        StringBuffer stringBuffer1 = new StringBuffer();
        new Thread(){
            @Override
            public void run() {
                synchronized (stringBuffer){
                    stringBuffer.append("a");
                    stringBuffer1.append("1");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    synchronized (stringBuffer1){
                        stringBuffer.append("b");
                        stringBuffer1.append("2");
                        System.out.println(stringBuffer);
                        System.out.println(stringBuffer1);
                    }
                }
            }
        }.start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (stringBuffer1){
                    stringBuffer.append("c");
                    stringBuffer1.append("3");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (stringBuffer){
                        stringBuffer.append("d");
                        stringBuffer1.append("4");
                        System.out.println(stringBuffer);
                        System.out.println(stringBuffer1);
                    }
                }
            }
        }).start();
    }
}

5.解决线程安全问题的方式3---lock锁

package top.oneluckyguy.thread;


import java.util.concurrent.locks.ReentrantLock;

import static java.lang.Thread.*;

/**
 * @author Liu Qingfeng
 * @create 2020-12-14----7:12
 * 解决线程安全问题的方式三: Lock锁  ----JDK5.0新增
 * 1.面试题:synchronized和Lock的异同
 * 相同:二者都可以解决线程安全问题
 * 不同:synchronized机制在执行完相应的同步代码块之后,自动释放同步监视器
 *       Lock要手动开启,同时需要手动unlock()
 * 优先使用顺序:lock--->同步代码块----->同步方法
 * 2.面试题
 * 如何解决线程安全问题,有几种方法?
 * 三种,详见代码
 */
public class LockTest {
    public static void main(String[] args) {
        Window3 window = new Window3();
        Thread thread = new Thread(window);
        Thread thread1 = new Thread(window);
        Thread thread2 = new Thread(window);
        thread.start();
        thread1.start();
        thread2.start();
    }
}
class Window3 implements Runnable{
    private int ticket = 100;
    private ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true) {
            try{
                lock.lock();
                if (ticket > 0){
                    try {
                        sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(currentThread().getName() + ":售票,票号为" + ticket);
                    ticket--;
                }else{
                    break;
                }
            }finally {
                lock.unlock();
            }

        }
    }
}

5.线程通信问题

1.两个线程交替打印1-100。

package top.oneluckyguy.java2;

/**
 * @author Liu Qingfeng
 * @create 2020-12-14----7:40
 * 线程通信的例子:使用两个线程打印1-100。线程一和线程二交替打印
 * wait():一旦执行此方法,当前线程就进入阻塞状态,并释放同步监视器
 * notify():一旦执行此方法,就会唤醒被wait()的一个线程,如果有多个线程被wait() 就会唤醒优先级高的。
 * notifyAll():一旦执行此方法,就会唤醒所有被wait()的线程。
 * 说明:1.上述三个方法必须使用在同步代码块和同步方法中Lock有其他方法在这里不介绍了
 *      2.上述三个方法的调用者必须是同步迪玛克或者同步方法中的同步监视器,否则,会出现异常。
 *      3.上述三个方法是定义在java.lang.Object中的不是定义在Thread中的。因为所有对象都可以调用,所以要定义在Object中
 * 面试题:sleep()和wait()的异同?
 * 相同:一旦执行此方法都可以使当前进程进入阻塞状态
 * 不同点:1).两个方法的声明位置不同:Thread类中声明sleep(),Object类中声明的 wait()。
 *        2).调用的要求不同,sleep()可以在任何需要的场景下调用,wait()必须要使用在同步代码块或者同步方法中由相同的同步监视器调用
 *        3).关于释放同步监视器:如果两个方法都使用在同步代码块或者同步方法中,sleep()不会释放锁,wait()会释放锁。
 */
public class CommunicationTest {
    public static void main(String[] args) {
        Number number = new Number();
        Thread thread = new Thread(number);
        Thread thread1 = new Thread(number);

        thread.setName("线程一");
        thread1.setName("线程二");

        thread.start();
        thread1.start();
    }
}
class Number implements Runnable{
    private int number = 1;
    @Override
    public void run() {
        while (true) {
            synchronized (this){       //这里是this,跟下面的默认要一致
                //唤醒阻塞的线程(优先等级高的)
                notify();             //这里默认是this.notify();
                if (number <= 100){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + number);
                    number++;
                    try {
                        //使得调用如下wait()方法的线程处于阻塞状态
                        wait();                 //这里默认是this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    break;
                }
            }
        }

    }
}

2.线程通信经典问题

package top.oneluckyguy.java2;

/**
 * @author Liu Qingfeng
 * @create 2020-12-14----8:30
 * 生产者(Productor)将产品交给店员(CLerk),而消费者(Customer)从店员处取走产品,店员一次只能持有固定数量的产品(比如:20),
 * 如果生产者试图生产更多的产品,店员会叫生产者停一下, 如果店中有空位放产品了再通知生产者继续生产;如果店中没有产品了,
 * 店员会告诉消费者等一下,如果店中有产品了再通知消费者来取走产品。
 * 分析:1.是否是多线程问题?是,生产者线程,消费者线程
 *     2.是否有共享数据?是,店员(或产品)
 *     3.如何解决线程的安全问题?同步机制,有三种方法
 *     4.是否涉及线程的通信?是
 *
 */
public class ProductTest{
    public static void main(String[] args) {
        Clerk clerk = new Clerk();

        Producter p1 = new Producter(clerk);
        p1.setName("生产者1:");

        Consumer c1 = new Consumer(clerk);
        c1.setName("消费者1");

        p1.start();
        c1.start();
    }
}

class Clerk{
    private int productCount = 0;
    //生产产品
    public synchronized void produceProduct() {
        if (productCount < 20){
            productCount++;
            System.out.println(Thread.currentThread().getName() +"开始生产第" + productCount + "个产品");
            notify();
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
//  消费产品
    public synchronized void consumeProduct() {
        if (productCount > 0){
            System.out.println(Thread.currentThread().getName() + "开始消费第" + productCount + "个产品");
            productCount--;
            notify();
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Producter extends Thread{
    private Clerk clerk;
    public Producter(Clerk clerk){
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println(getName()+"开始生产产品...........");
        while(true){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.produceProduct();
        }
    }
}
class Consumer extends Thread{
    private Clerk clerk;
    public Consumer(Clerk clerk){
        this.clerk = clerk;
    }
    @Override
    public void run() {
        System.out.println(getName()+"开始消费产品...........");
        while(true){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.consumeProduct();
        }
    }
}

6.Callable

package top.oneluckyguy.java2;

import sun.print.SunMinMaxPage;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author Liu Qingfeng
 * @create 2020-12-20----0:28
 * 如何理解实现Callable接口的方式创建多线程比实现Runnable方法强大:
 * 1.Callable方法可以抛出异常,被外面的操作捕获,获取异常信息
 * 2.Callable可以有返回值
 * 3.Callable是支持泛型的
 */

public class CallableTest {
    public static void main(String[] args) {
        //3.创建callable接口实现类的对象
        NumThread numThread = new NumThread();
        //4.将此Callable接口实现类的对象作为传递到Future Task构造器中创建FutureTask对象
        FutureTask futureTask = new FutureTask(numThread);
        Object sum = null;
        //5.将FutureTask的对象作为参数产地到Thread类的构造器中,创建Thread对象并调用start();
        new Thread(futureTask).start();
        try {
            //6.可有可无。。获取Callable中call方法的返回值
            //get()返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值
            sum = futureTask.get();
            System.out.println(sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}
//1.创建一个实现Callable的实现类
class NumThread implements Callable{
    //2.实现call方法将此线程需要执行的操作放在此方法中
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 0; i <= 100 ; i++) {
            if(i % 2 == 0){
                System.out.println(i);
                sum += i;
            }
        }
        return sum;
    }
}

7.线程池

package com.atguigu.java2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 创建线程的方式四:使用线程池
 *
 * 好处:
 * 1.提高响应速度(减少了创建新线程的时间)
 * 2.降低资源消耗(重复利用线程池中线程,不需要每次都创建)
 * 3.便于线程管理
 *      corePoolSize:核心池的大小
 *      maximumPoolSize:最大线程数
 *      keepAliveTime:线程没有任务时最多保持多长时间后会终止
 *
 *
 * 面试题:创建多线程有几种方式?四种!
 * @author shkstart
 * @create 2019-02-15 下午 6:30
 */

class NumberThread implements Runnable{

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

class NumberThread1 implements Runnable{

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

public class ThreadPool {

    public static void main(String[] args) {
        //1. 提供指定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);
        ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
        //设置线程池的属性
//        System.out.println(service.getClass());
//        service1.setCorePoolSize(15);
//        service1.setKeepAliveTime();


        //2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象
        service.execute(new NumberThread());//适合适用于Runnable
        service.execute(new NumberThread1());//适合适用于Runnable

//        service.submit(Callable callable);//适合使用于Callable
        //3.关闭连接池
        service.shutdown();
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值