Java多线程的创建

多线程

线程的创建

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毫秒时间内,当前线程不得分配CPU

  10. isAlive()

    判断当前线程是否存活

线程的优先级:

  1. 优先级的表示:

    • 最高优先级:MAX_PRIORITY:10
    • 最低优先级:MIN _PRIORITY:1
    • 默认优先级:NORM_PRIORITY:5
  2. 如何获取和设置当前线程的优先级:

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

    说明:高优先级线程更容易抢占到CPU,不意味着只有高优先级线程执行完毕低优先级线程才会被执行

方式一:继承于Thread类

  1. 创建一个继承于Thread类的子类
  2. 重写Thread类的run() 方法,将此线程执行的操作声明在run()中
  3. 创建Thread类的子类的对象
  4. 通过此对象调用start()

注意:

  • 不能通过直接调用run()的方式启动线程
  • 同一个线程不可以多次调用start()方法去执行,否则会出现IllegalThreadStateException
//1.创建一个继承于Thread类的子类
class Window extends Thread{
    private static int tickets = 100;

//2.重写Thread类的run()方法,将此线程执行的操作声明在run()中
    @Override
    public void run() {
        while(true){
            if(tickets>0){
                System.out.println(currentThread().getName()+"卖票,票号为"+tickets);
            tickets--;
            }else{
                break;
            }
        }
    }
}


public class TicketWindow {
    public static void main(String[] args) {
//3.创建Thread类的子类的对象
        Window w1 = new Window();
        Window w2 = new Window();
        Window w3 = new Window();

        w1.setName("窗口1");
        w2.setName("窗口2");
        w3.setName("窗口3");

//4.通过此对象调用start()
        w1.start();
        w2.start();
        w3.start();
    }
}

执行结果

窗口2卖票,票号为100//存在线程安全问题
窗口3卖票,票号为100//存在线程安全问题
窗口1卖票,票号为100//存在线程安全问题
窗口3卖票,票号为98
窗口2卖票,票号为99
窗口3卖票,票号为96
窗口1卖票,票号为97
窗口3卖票,票号为94
...

方式二:实现Runnable接口

  1. 创建一个实现了Runnable接口的类
  2. 实现类去实现Runnable中的抽象方法:run()
  3. 创建实现类的对象
  4. 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
  5. 通过Thread类的对象调用start()
//1.创建一个实现了Runnable接口的类
class Window2 implements Runnable {
    private int tickets = 100;

//2.实现类去实现Runnable中的抽象方法:run()
    @Override
    public void run() {
        while (true) {
            if (tickets > 0) {
                System.out.println(Thread.currentThread().getName() + "卖票,票号为" + tickets);
                tickets--;
            } else {
                break;
            }
        }
    }
}


public class TicketWindow2 {
    public static void main(String[] args) {
//3.创建实现类的对象
        Window2 window2 = new Window2();
//4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
        Thread w1 = new Thread(window2);
        Thread w2 = new Thread(window2);
        Thread w3 = new Thread(window2);
       
        w1.setName("窗口1");
        w2.setName("窗口2");
        w3.setName("窗口3");

//4.通过Thread类的对象调用start()
        w1.start();
        w2.start();
        w3.start();
    }
}

执行结果

窗口3卖票,票号为100//存在线程安全问题
窗口2卖票,票号为100//存在线程安全问题
窗口1卖票,票号为100//存在线程安全问题
窗口2卖票,票号为98
窗口3卖票,票号为99
窗口2卖票,票号为96
...

比较创建线程的两种方式。

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

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

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

联系:public class Thread implements Runnable
相同点:两种方式都需要重写run(),将线程要执行的逻辑声明在run()中。

方式三:实现Callable接口

  1. 创建一个实现Callable接口的实现类
  2. 实现Call方法,将此线程执行的操作声明在方法中
  3. 创建实现Callable接口类的对象
  4. 将此实现Callable接口类的对象作为参数传递到FutureTask构造器中,创建FutureTask的对象
  5. 将FutureTask的对象作为参数传递到Thread类中,创建Thread类对象,调用start方法
  6. 可使用FutureTask类的get方法获取Callable中call方法的返回值(用途:主线程可以获取其他线程的结果)

如何理解实现Callable接口比实现Runable接口更加强大:

    1. call()可以有返回值的。
    1. call()可以抛出异常,被外面的操作捕获,获取异常的信息
    1. Callable是支持泛型
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

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

public class ThreadNew {
    public static void main(String[] args) {
        //3.创建实现Callable接口类的对象
        NumThread numThread = new NumThread();
        //4.将此实现Callable接口类的对象作为参数传递到FutureTask构造器中,创建FutureTask的对象
        FutureTask futureTask = new FutureTask(numThread);
        //5.将FutureTask的对象作为参数传递到Thread类中,创建Thread类对象,调用start方法
        new Thread(futureTask).start();
        //6.可使用FutureTask类的get方法获取Callable中call方法的返回值
        //get()返回值即为FutureTask构造器Callable实现类重写的call()发返回值
        //用途:主线程可以获取其他线程的结果
        try {
            Object sum = futureTask.get();
            System.out.println("总和为:" + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

方式四:使用线程池

  1. 提供指定线程数量的线程池
  2. 执行指定线程的操作需要提供实现Runable和Callable接口的类的对象
  3. 调用execute(适用于Runable接口)或submit(适用于Callable接口)方法执行线程
  4. 关闭线程池
package day01;

import java.util.concurrent.*;

class NumberThread1 implements Runnable {
    int sum = 0;

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

class NumberThread2 implements Callable {
    int sum = 0;

    @Override
    public Object call() throws Exception {
        for (int i = 0; i <= 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
                sum += i;
            }
        }
        return sum;
    }
}

public class ThreadPool {

    public static void main(String[] args) {
        //1.提供指定线程数量的线程池
        //service为实现ExecutorService接口的匿名类的对象
        ExecutorService service = Executors.newFixedThreadPool(10);

        //转换类型可使用set方法设置属性
        System.out.println(service.getClass());
        ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;


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

        //service.submit适用于Callable接口
        NumberThread2 numberThread2 = new NumberThread2();
        FutureTask futureTask = new FutureTask(numberThread2);
        service.submit(futureTask);
        try {
            Object sum = futureTask.get();
            System.out.println("所有的偶数和为:" + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        //3.关闭线程池
        service.shutdown();
    }
}

线程的安全问题(同步机制)

  1. 问题出现的原因:

    多个线程有共享数据,在某个线程执行过程中,尚未完成操作而被阻塞,其他线程抢占运行,从而引发线程安全问题。

  2. 问题的解决:

    当一个线程在进行操作时,其他线程无法参与,直到此线程操作完毕。(线程的同步)

同步机制一:同步代码块

使用方法:

synchronized(同步监视器){
    //需要被同步的代码
}

说明:

  1. 同步代码块:操作共享数据的代码,即为需要被同步的代码
  2. 共享数据:即为多个线程要操作的共享数据
  3. 同步监视器:俗称:“锁”,任何一个类的对象,都可以充当锁。但是多个被同步的线程必须共用同一个锁。
class Window2 implements Runnable {
    private int tickets = 100;
    
    //创建同步监视器
    Object obj = new Object();

    @Override
    public void run() {
        while (true) {
            
    //使用同步代码块的方法,同步共享数据
            synchronized(obj) {
                if (tickets > 0) {
                    System.out.println(Thread.currentThread().getName() + "卖票,票号为" + tickets);
                    tickets--;
                } else {
                    break;
                }
            }
            
            
        }
    }
}


public class TicketWindow2 {
    public static void main(String[] args) {

        Window2 window2 = new Window2();

        Thread w1 = new Thread(window2);
        Thread w2 = new Thread(window2);
        Thread w3 = new Thread(window2);

        w1.setName("窗口1");
        w2.setName("窗口2");
        w3.setName("窗口3");

        w1.start();
        w2.start();
        w3.start();
    }
}
class Window extends Thread{
    private static int tickets = 100;
        
    //创建同步监视器(创建静态对象保证同步监视器只有一个)
    private static Object obj = new Object();
    
    @Override
    public void run() {
        while(true){
            
    //使用同步代码块的方法,同步共享数据
            synchronized(obj) {
                if (tickets > 0) {
                    System.out.println(currentThread().getName() + "卖票,票号为" + tickets);
                    tickets--;
                } else {
                    break;
                }
            }
            
        }
    }
}

public class TicketWindow {
    public static void main(String[] args) {

        Window w1 = new Window();
        Window w2 = new Window();
        Window w3 = new Window();

        w1.setName("窗口1");
        w2.setName("窗口2");
        w3.setName("窗口3");

        w1.start();
        w2.start();
        w3.start();
    }
}

补充:(保证同步监视器唯一即可)

  1. 在实现Ranable接口的创建多线程的方式中,可以考虑使用this作为同步监视器。
  2. 在继承Thread类创建多线程的方式中,需要谨慎使用this作为同步监视器。
  3. 在继承Thread类创建多线程的方式中,可以使用 “类.class” 作为同步监视器。

同步机制二:同步方法

如果操作共享数据的代码完整的声明在一个方法中,可以将方法声明为同步的。

使用synchronized修饰方法,使方法成为同步的,同步方法的默认监视器为this。

同步方法在实现Runable接口创建多线程中的使用:

class Window2 implements Runnable {
    private int tickets = 100;
    
    @Override
    public void run() {
        while (tickets>0) {
            show();
        }
    }
    
//同步监视器默认为this
    private synchronized void show(){
        if (tickets > 0) {
            System.out.println(Thread.currentThread().getName() + "卖票,票号为" + tickets);
            tickets--;
        }
    }
}


public class TicketWindow2 {
    public static void main(String[] args) {
        Window2 window2 = new Window2();
        
        Thread w1 = new Thread(window2);
        Thread w2 = new Thread(window2);
        Thread w3 = new Thread(window2);

        w1.setName("窗口1");
        w2.setName("窗口2");
        w3.setName("窗口3");
        
        w1.start();
        w2.start();
        w3.start();
    }
}

同步方法在继承Thread类创建多线程中的使用:

class Window extends Thread {
    private static int tickets = 100;

    @Override
    public void run() {
        while (tickets>0) {
            show();
        }
    }

//此处同步方法需声明文静态,保证同步监视器唯一为:Window.class
    private static synchronized void show(){
        if (tickets > 0) {
            System.out.println(currentThread().getName() + "卖票,票号为" + tickets);
            tickets--;
        }
    }
}


public class TicketWindow {
    public static void main(String[] args) {

        Window w1 = new Window();
        Window w2 = new Window();
        Window w3 = new Window();

        w1.setName("窗口1");
        w2.setName("窗口2");
        w3.setName("窗口3");

        w1.start();
        w2.start();
        w3.start();
    }
}

说明:

  1. 非静态的同步方法,同步监视器为:this。
  2. 静态的统发方法,同步监视器为当前类本身:“当前类.class” 。

同步机制三:手动使用Lock锁

import java.util.concurrent.locks.ReentrantLock;

class Window3 implements Runnable {
    private int tickets = 100;
    //1.实例化ReentrantLock
    private ReentrantLock lock = new ReentrantLock();

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

            try {
//2.调用lock()方法
                lock.lock();
                if (tickets > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "卖票,票号为" + tickets);
                    tickets--;
                } else {
                    break;
                }
            } finally {
//3.调用unlock()方法解锁
                lock.unlock();
            }
        }
    }
}


public class LockTest2 {
    public static void main(String[] args) {
        Window3 window3 = new Window3();

        Thread w1 = new Thread(window3);
        Thread w2 = new Thread(window3);
        Thread w3 = new Thread(window3);

        w1.setName("窗口1");
        w2.setName("窗口2");
        w3.setName("窗口3");

        w1.start();
        w2.start();
        w3.start();
    }
}

说明:

  1. 此方法为JDK5.0后新增
  2. ReentrantLock类提供两个构造器,传参构造器中传入true将形成阻塞队列,线程先进先出,无参构造器线程相互抢占

死锁

死锁出现的情况:不同的线程分别占用对方所需要的同步资源均不放弃,则形成死锁。出现死锁时,各个线程都处于阻塞状态,线程无法继续运行或死亡。因此当我们在使用同步的时候,需要避免发生死锁。

死锁演示:以下代码中,分别使用继承Thread类创建匿名对象的方法(线程一)和创建实现Runable接口的匿名实现类的方法(线程二)创建两个线程,s1,s2分别为两个不同的“锁”,线程一在取得s1资源后休眠后企图获得s2资源,线程二在取得s2资源后休眠后企图获得s1资源,两个线程均不能获得所有资源后释放资源,并且两个线程都占用对方资源,导致死锁发生。

public class LockTest {
    public static void main(String[] args) {
        //创建两个同步监视器(锁)
        StringBuffer s1 = new StringBuffer();
        StringBuffer s2 = new StringBuffer();

        new Thread() {
            @Override
            public void run() {

                //获取同步资源s1
                synchronized (s1) {
                    s1.append("a");
                    s2.append("1");

                    //休眠
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    
                    //在掌握资源s1的情况下企图获取资源s2
                    synchronized(s2){
                        s1.append("b");
                        s2.append("2");
                    }
                    System.out.println(s1);
                    System.out.println(s2);
                }
            }
        }.start();


        new Thread(new Runnable() {
            @Override
            public void run() {
                
                //获取同步资源s2
                synchronized (s2) {
                    s1.append("c");
                    s2.append("3");

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

                    //在掌握资源s1的情况下企图获取资源s1
                    synchronized(s1){
                        s1.append("d");
                        s2.append("4");
                    }
                    System.out.println(s1);
                    System.out.println(s2);
                }
            }
        }).start();
    }
}

线程的通信

  • wait():一旦执行此方法,当前线程就进入阻塞状态,并释放同步监视器。
  • notify():一旦执行此方法,就会唤醒被wait的一个线程。如果有多个线程被wait,就唤醒优先级高的那个。
  • notifyAll():一旦执行此方法,就会唤醒所有被wait的线程。

说明:

三个方法必须使用在同步代码块或同步方法中。

  1. wait(),notify(),notifyAll()三个方法必须使用在同步代码块或同步方法中。
  2. wait(),notify(),notifyAll()三个方法的调用者必须是同步代码块或同步方法中的同步监视器。否则,会出现IllegalMonitorStateException异常
  3. wait(),notify(),notifyAll()三个方法是定义在java.lang.Object类中。
class Number implements Runnable{
    private int number = 1;
    @Override
    public void run() {
        while(true){
            synchronized (this) {

                notify();//唤醒其他阻塞线程
                if (number <= 100){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + number);
                    number ++;

                    try {
                        wait();//阻塞本线程
                    } catch (InterruptedException e) {
                        e.printStackTrace();

                    }
                }else{
                    break;
                }
            }
        }
    }
}
public class CommunicationTest {
    public static void main(String[] args) {
        Number num = new Number();
        Thread t1 = new Thread(num);
        Thread t2 = new Thread(num);


        t1.setName("甲");
        t2.setName("乙");

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

生产者消费者问题

  • 生产者(Productor)将产品交给店员(Clerk),而消费者(Customer)从店员处取走产品,
  • 店员一次只能持有固定数量的产品(比如:20),只有店员手中有产品时消费者才能从店员手中取产品,只有店员手中的产品数量小于最大值时,生产者才可以生产产品给店员。
class Clerk{
    int productCount = 0;

    public synchronized void consumeProduct() {
        if(productCount < 20){
            productCount++;
            System.out.println(Thread.currentThread().getName() + "生产者生产第" + productCount + "件产品");
            notify();
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void produceProduct() {

        if (productCount > 0) {
            System.out.println(Thread.currentThread().getName() + "消费者消费第" + productCount + "件产品");
            productCount--;
            notify();
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Consumer extends Thread{

    private Clerk clerk;

    Consumer(Clerk clerk){
        this.clerk=clerk;
    }

    @Override
    public void run() {
        System.out.println("消费者开始消费....");
        while (true){
            try {
                sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.consumeProduct();
        }
    }
}

class Producer extends Thread{

    private Clerk clerk;

    Producer(Clerk clerk){
        this.clerk=clerk;
    }

    @Override
    public void run() {
        System.out.println("生产者开始生产....");
        while (true){
            try {
                sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.produceProduct();
        }
    }
}

public class ProdectTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Consumer consumer1 = new Consumer(clerk);
        Producer producer1 = new Producer(clerk);
        consumer1.setName("生产者1:");
        producer1.setName("消费者1:");
        producer1.start();
        consumer1.start();

    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值