Java_11 多线程与锁

jia-ming / 2024-02-22 / 原文

title:(在线学习平台) link:(https://www.acwing.com/) cover:(https://cdn.acwing.com/media/activity/surface/log.png)

1 多线程

1.1 实现多线程

写法1:继承Thread

class Worker extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10; i ++ ) {
            System.out.println("Hello! " + this.getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Worker worker1 = new Worker();
        Worker worker2 = new Worker();
        worker1.setName("thread-1");
        worker2.setName("thread-2");
        worker1.start();
        worker2.start();
    }
}

写法2:实现Runnable接口

class Worker1 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i ++ ) {
            System.out.println("Hello! " + "thread-1");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

class Worker2 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i ++ ) {
            System.out.println("Hello! " + "thread-2");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        new Thread(new Worker1()).start();
        new Thread(new Worker2()).start();
    }
}

1.2 常用API

  1. start():开启一个线程
  2. Thread.sleep(): 休眠一个线程
  3. join():等待线程执行结束(才会继续执行主线程等)
  4. interrupt():从休眠中中断线程
  5. setDaemon():将线程设置为守护线程。当只剩下守护线程时,程序自动退出;应用:当需要一个线程在其他线程结束之后自动结束,就可以将其设成守护线程

image
image

  • interrupt():从休眠中中断线程
    image
    image

  • setDaemon():将线程设置为守护线程
    image

2 锁

  • lock:获取锁,如果锁已经被其他线程获取,则阻塞
  • unlock:释放锁,并唤醒被该锁阻塞的其他线程
import java.util.concurrent.locks.ReentrantLock;
class Worker extends Thread {
    public static int cnt = 0;
    private static final ReentrantLock lock = new ReentrantLock();


    @Override
    public void run() {
        for (int i = 0; i < 100000; i ++ ) {
            lock.lock();
            try {
                cnt ++ ;
            } finally {
                lock.unlock();
            }
        }
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Worker worker1 = new Worker();
        Worker worker2 = new Worker();

        worker1.start();
        worker2.start();
        worker1.join();
        worker2.join();

        System.out.println(Worker.cnt);
    }
}

3 同步(Synchronized)

写法1:将Synchronized加到代码块上

class Count {
    public int cnt = 0;
}

class Worker extends Thread {
    public final Count count;

    public Worker(Count count) {
        this.count = count;
    }

    @Override
    public void run() {
        synchronized (count) {
            for (int i = 0; i < 100000; i ++ ) {
                count.cnt ++ ;
            }
        }
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Count count = new Count();

        Worker worker1 = new Worker(count);
        Worker worker2 = new Worker(count);

        worker1.start();
        worker2.start();
        worker1.join();
        worker2.join();

        System.out.println(count.cnt);
    }
}

写法2:将Synchronized加到函数上(锁加到了this对象上)

class Worker implements Runnable {
    public static int cnt = 0;

    private synchronized void work() {
        for (int i = 0; i < 100000; i ++ ) {
            cnt ++ ;
        }
    }

    @Override
    public void run() {
        work();
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Worker worker = new Worker();
        Thread worker1 = new Thread(worker);
        Thread worker2 = new Thread(worker);

        worker1.start();
        worker2.start();
        worker1.join();
        worker2.join();

        System.out.println(Worker.cnt);
    }
}

3.1 wait与notify

package org.yxc;

class Worker extends Thread {
    private final Object object;
    private final boolean needWait;

    public Worker(Object object, boolean needWait) {
        this.object = object;
        this.needWait = needWait;
    }

    @Override
    public void run() {
        synchronized (object) {
            try {
                if (needWait) {
                    object.wait();
                    System.out.println(this.getName() + ": 被唤醒啦!");
                } else {
                    object.notifyAll();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Object object = new Object();
        for (int i = 0; i < 5; i ++ ) {
            Worker worker = new Worker(object, true);
            worker.setName("thread-" + i);
            worker.start();
        }

        Worker worker = new Worker(object, false);
        worker.setName("thread-" + 5);
        Thread.sleep(1000);
        worker.start();
    }
}