21xrx.com
2024-11-22 08:01:05 Friday
登录
文章检索 我的文章 写文章
Java多线程设计模式的代码实现图解
2023-06-22 04:11:19 深夜i     --     --
Java 多线程 设计模式 代码实现 图解

Java是一门支持多线程的编程语言,它内置了一些常用的多线程设计模式,这些模式可以帮助开发者更好地编写高效稳定的多线程程序,在实际开发中也常常用到。本文将通过图解的方式介绍Java多线程设计模式的代码实现。

1. 生产者消费者模式

生产者消费者模式是一种常见的多线程模式,它通过一个生产者线程和一个或多个消费者线程之间的协作完成数据的生产和消费。以下是生产者消费者模式的代码实现:


public class ProducerConsumerPattern {

  public static void main(String[] args) {

    Buffer buffer = new Buffer();

    Producer producer = new Producer(buffer);

    Consumer consumer = new Consumer(buffer);

    producer.start();

    consumer.start();

  }

}

class Buffer {

  private int num;

  private boolean flag = false;

  public synchronized void put(int num) {

    while (flag) {

      try {

        wait();

      } catch (InterruptedException e) {

        e.printStackTrace();

      }

    }

    this.num = num;

    System.out.println("Produced " + num);

    flag = true;

    notify();

  }

  public synchronized int get() {

    while (!flag) {

      try {

        wait();

      } catch (InterruptedException e) {

        e.printStackTrace();

      }

    }

    System.out.println("Consumed " + num);

    flag = false;

    notify();

    return num;

  }

}

class Producer extends Thread {

  private Buffer buffer;

  public Producer(Buffer buffer)

    this.buffer = buffer;

  

  @Override

  public void run() {

    for (int i = 1; i <= 10; i++) {

      buffer.put(i);

    }

  }

}

class Consumer extends Thread {

  private Buffer buffer;

  public Consumer(Buffer buffer)

    this.buffer = buffer;

  

  @Override

  public void run() {

    for (int i = 1; i <= 10; i++) {

      buffer.get();

    }

  }

}

2. 观察者模式

观察者模式是一种常用的多线程模式,它定义了一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都会得到通知。以下是观察者模式的代码实现:


public class ObserverPattern {

  public static void main(String[] args) {

    ConcreteSubject subject = new ConcreteSubject();

    ConcreteObserver observer1 = new ConcreteObserver("Observer1");

    ConcreteObserver observer2 = new ConcreteObserver("Observer2");

    subject.attach(observer1);

    subject.attach(observer2);

    subject.setState("Hello, world!");

  }

}

interface Subject {

  void attach(Observer observer);

  void detach(Observer observer);

  void notifyObservers();

}

class ConcreteSubject implements Subject {

  private List<Observer> observers = new ArrayList<>();

  private String state;

  public String getState()

    return state;

  

  public void setState(String state) {

    this.state = state;

    notifyObservers();

  }

  @Override

  public void attach(Observer observer) {

    observers.add(observer);

  }

  @Override

  public void detach(Observer observer) {

    observers.remove(observer);

  }

  @Override

  public void notifyObservers() {

    for (Observer observer : observers) {

      observer.update(state);

    }

  }

}

interface Observer {

  void update(String state);

}

class ConcreteObserver implements Observer {

  private String name;

  public ConcreteObserver(String name)

    this.name = name;

  

  @Override

  public void update(String state) {

    System.out.println(name + " received message: " + state);

  }

}

3. 策略模式

策略模式是一种常见的多线程模式,它将算法的实现和使用分离,使用策略模式可以让算法的变化独立于使用它的客户端。以下是策略模式的代码实现:


public class StrategyPattern {

  public static void main(String[] args) {

    Context context = new Context(new ConcreteStrategyA());

    context.executeStrategy();

    context = new Context(new ConcreteStrategyB());

    context.executeStrategy();

    context = new Context(new ConcreteStrategyC());

    context.executeStrategy();

  }

}

interface Strategy {

  void execute();

}

class ConcreteStrategyA implements Strategy {

  @Override

  public void execute() {

    System.out.println("Execute strategy A.");

  }

}

class ConcreteStrategyB implements Strategy {

  @Override

  public void execute() {

    System.out.println("Execute strategy B.");

  }

}

class ConcreteStrategyC implements Strategy {

  @Override

  public void execute() {

    System.out.println("Execute strategy C.");

  }

}

class Context {

  private Strategy strategy;

  public Context(Strategy strategy)

    this.strategy = strategy;

  

  public void setStrategy(Strategy strategy)

    this.strategy = strategy;

  

  public void executeStrategy() {

    strategy.execute();

  }

}

以上是Java多线程设计模式的代码实现图解,这些模式可以帮助开发者更好地编写高效稳定的多线程程序。在实际开发中,开发者可能会根据具体的业务需求采用不同的多线程设计模式。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复