蓝桥杯Java课程学习——多线程(一)




实现多线程

Java 中的Thread类就是专门用来创建线程和操作线程的类。

创建线程

创建线程的方法:

  • 继承 Thread 类并重写它的run()方法,然后用这个子类来创建对象并调用 start() 方法。
  • 定义一个类并实现Runnable接口,实现run()方法。

总的来说就是线程通过start()方法启动而不是run()方法,run() 方法的内容为我们要实现的业务逻辑。

public class CreateThread {

    public static void main(String[] args) {
        Thread1 thread1 = new Thread1();
        //声明一个Thread1对象,这个Thread1类继承自Thread类的

        Thread thread2 = new Thread(new Thread2());
        //传递一个匿名对象作为参数

        thread1.start();
        thread2.start();
        //启动线程
    }
}

class Thread1 extends Thread {
    @Override
    public void run() {
        //在run()方法中放入线程要完成的工作

        //这里我们把两个线程各自的工作设置为打印100次信息
        for (int i = 0; i < 100; ++i) {
            System.out.println("Hello! This is " + i);
        }

        //在这个循环结束后,线程便会自动结束
    }
}

class Thread2 implements Runnable {
    //与Thread1不同,如果当一个线程已经继承了另一个类时,就建议你通过实现Runnable接口来构造

    @Override
    public void run() {
        for (int i = 0; i < 100; ++i) {
            System.out.println("Thanks. There is " + i);
        }
    }
}

你在控制台就可以看到两个线程近似交替地在输出信息。受到系统调度的影响,两个线程输出信息的先后顺序可能不同。

线程变量:ThreadLocal

public class ThreadLocalDemo{
    public static void main(String[] args){
        ThreadDemo threadDemo = new ThreadDemo();

        new Thread(threadDemo).start();
        new Thread(threadDemo).start();
    }
}

class ThreadDemo implements Runnable
{
    private Integer integer = 0;
    //private static ThreadLocal<Integer> threadLocal 
    //    = ThreadLocal.withInitial(() -> 0);

    public void run(){
        for(int i = 0; i < 10; i++){
            //Integer integer = threadLocal.get();
            integer += 1;
            //threadLocal.set(integer);
            System.out.println(integer);
        }
    }
}
  • ThreadLocal加入后可以保证线程间的变量都是独立的

在没有加入ThreadLocal 的情况下,发现 integer 变量的值增加到了 20,那是因为这个时候两个线程都是使用同一对象threadDemo的变量,这个时候的integer就变成了线程共享变量,如果同学们多运行几次,还有可能出现最后结果是 18 19 的情况,那是因为如果不做任何处理,线程共享变量都不是线程安全的,也就是说在多线程的情况下,共享变量有可能会出错。

线程同步

线程同步可以保证在同一个时刻该对象只被一个线程访问

Synchronized

关键字synchronized可以修饰方法或者以同步块的形式来进行使用,它确保多个线程在同一个时刻,只能有一个线程处于方法或者同步块中,保证了线程对变量访问的可见性和排他性。它有三种使用方法:

  • 对普通方式使用,将会锁住当前实例对象。
  • 对静态方法使用,将会锁住当前类的 Class 对象。
  • 对代码块使用,将会锁住代码块中的对象。
public class SynchronizedDemo {
    private static Object lock = new Object();

    public static void main(String[] args) {
        //同步代码块 锁住lock
        synchronized (lock) {
            //doSomething
        }
    }

    //静态同步方法  锁住当前类class对象
    public synchronized static void staticMethod(){

    }
    //普通同步方法  锁住当前实例对象
    public synchronized void memberMethod() {

    }
}

java.util.concurrent

java.util.concurrent 包是 java5 开始引入的并发类库,提供了多种在并发编程中的适用工具类。包括原子操作类,线程池,阻塞队列,Fork/Join 框架,并发集合,线程同步锁等。

Lock 与 Unlock

JUC 中的 ReentrantLock 是多线程编程中常用的加锁方式,ReentrantLock加锁比 synchronized 加锁更加的灵活,提供了更加丰富的功能。

练习

import java.util.concurrent.locks.ReentrantLock;

public class LockDemo {
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
    	//lambda表达式,重写run()方法
        Thread thread1 = new Thread(() -> {
            lock.lock();
            try {
                //需要同步的代码块
                System.out.println("线程1加锁");
            }finally {
//                一定要在finally中解锁,否则可能造成死锁
                lock.unlock();
                System.out.println("线程1解锁");
            }
        });
        thread1.start();
		
		//lambda表达式,重写run()方法
        Thread thread2 = new Thread(() -> {
            lock.lock();
            try {
                System.out.println("线程2加锁");
            }finally {
                lock.unlock();
                System.out.println("线程2解锁");
            }
        });
        thread2.start();
    }

}

死锁

public class DeadLockDemo {
    private static Object lockA = new Object();
    private static Object lockB = new Object();

    public static void main(String[] args) {
        //这里使用lambda表达式创建了一个线程
        //线程  1
        new Thread(() -> {
            synchronized (lockA) {
                try {
                    //线程休眠一段时间  确保另外一个线程可以获取到b锁
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("D");
                synchronized (lockB) {
                }
            }
        }).start();
        //线程 2
        new Thread(() -> {
            synchronized (lockB) {
                System.out.println("死锁...");
                synchronized (lockA) {
                }
            }
        }).start();
    }
}

在上面代码中,线程 1 获取了lockA的锁后再去获取lockB的锁,而此时lockB已经被线程 2 获取,同时线程 2 也想获取lockA,两个线程进这样僵持了下去,谁也不让,造成了死锁。在编程时,应该避免死锁的出现。

线程生命周期

线程的声明周期共有 6 种状态,分别是:新建New、运行(可运行)Runnable、阻塞Blocked、计时等待Timed Waiting、等待Waiting 和终止Terminate

当你声明一个线程对象时,线程处于新建状态,系统不会为它分配资源,它只是一个空的线程对象。

调用 start() 方法时,线程就成为了可运行状态,至于是否是运行状态,则要看系统的调度了。

调用了 sleep() 方法、调用 wait() 方法和 IO 阻塞时,线程处于等待、计时等待或阻塞状态。

当 run() 方法执行结束后,线程也就终止了。

实例

ThreadState

public class ThreadState implements Runnable {

    public synchronized void waitForAMoment() throws InterruptedException {

        wait(500);
        //使用wait()方法使当前线程等待500毫秒
        //或者等待其他线程调用notify()或notifyAll()方法来唤醒
    }

    public synchronized void waitForever() throws InterruptedException {

        wait();
        //不填入时间就意味着使当前线程永久等待,
        //只能等到其他线程调用notify()或notifyAll()方法才能唤醒
    }

    public synchronized void notifyNow() throws InterruptedException {

        notify();
        //使用notify()方法来唤醒那些因为调用了wait()方法而进入等待状态的线程
    }

    @Override
    public void run() {

        //这里用异常处理是为了防止可能的中断异常
        //如果任何线程中断了当前线程,则抛出该异常

        try {
            waitForAMoment();
            // 在新线程中运行waitMoment()方法

            waitForever();
            // 在新线程中运行waitForever()方法

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

ThreadTest测试类

public class ThreadTest {
    public static void main(String[] args) throws InterruptedException {
        ThreadState state = new ThreadState();
        //声明并实例化一个ThreadState对象

        Thread thread = new Thread(state);
        //利用这个名为state的ThreadState对象来创建Thread对象

        System.out.println("Create new thread: " + thread.getState());
        //使用getState()方法来获得线程的状态,并进行输出

        thread.start();
        //使用thread对象的start()方法来启动新的线程

        System.out.println("Start the thread: " + thread.getState());
        //输出线程的状态

        Thread.sleep(100);
        //通过调用sleep()方法使当前这个线程休眠100毫秒,从而使新的线程运行waitForAMoment()方法

        System.out.println("Waiting for a moment (time): " + thread.getState());
        //输出线程的状态

        Thread.sleep(1000);
        //使当前这个线程休眠1000毫秒,从而使新的线程运行waitForever()方法

        System.out.println("Waiting for a moment: " + thread.getState());
        //输出线程的状态

        state.notifyNow();
        // 调用state的notifyNow()方法

        System.out.println("Wake up the thread: " + thread.getState());
        //输出线程的状态

        Thread.sleep(1000);
        //使当前线程休眠1000毫秒,使新线程结束

        System.out.println("Terminate the thread: " + thread.getState());
        //输出线程的状态
    }
}

线程同步练习

你需要完成以下需求:

  • 创建三个线程输出 A、B、C 三个字符。
  • 要求 A、B、C 必须顺序输出,连续输出三次。

结果如下

A
B
C
A
B
C
A
B
C

代码:

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadTest {
    private static ReentrantLock lock = new ReentrantLock();
    private static int count = 0;
    private static Condition condition = lock.newCondition();

    public static void main(String[] args) {
        Thread A = new Thread(() -> {
        //加锁 一次只有一个线程输出
            lock.lock();
            try {
                while (true) {
                //因为只循环3次 所以到9的时候就结束循环
                    if (count == 9) {
                        break;
                    }
                    //当余数为0 就输出A
                    if (count % 3 == 0) {
                        count++;
                        System.out.println("A");
                        //唤醒其他等待线程
                        condition.signalAll();
                    } else {
                        try {
                        //等待
                            condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } finally {
                lock.unlock();
            }
        });
        Thread B = new Thread(() -> {
            lock.lock();
            try {
                while (true) {
                    if (count == 9) {
                        break;
                    }
                    if (count % 3 == 1) {
                        count++;
                        System.out.println("B");
                        condition.signalAll();
                    } else {
                        try {
                            condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } finally {
                lock.unlock();
            }
        });
        Thread C = new Thread(() -> {
            lock.lock();
            try {
                while (true) {
                    if (count == 9) {
                        break;
                    }
                    if (count % 3 == 2) {
                        count++;
                        System.out.println("C");
                        condition.signalAll();
                    } else {
                        try {
                            condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } finally {
                lock.unlock();
            }
        });

        A.start();
        B.start();
        C.start();

    }
}

相关文章

蓝桥杯Java课程学习——多线程(二)

蓝桥杯Java课程学习——多线程(二)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值