多线程编程---两个线程交替打印1-100 Java并发编程经典热点面试题

方法1:使用synchronized同步代码块

首先要创建一个锁对象;再将两个线程的核心代码同步起来;

(本人并没有使用lambda表达式的方法创建线程)
(^ _ ^)

package org.example;



/**
 * @author lhd
 * @version 1.0
 * @date 2024/5/26 22:11
 */
public class TwoThread {
    static /*volatile*/ int cnt = 1;
    static Object lock = new Object();
    static class thread1 extends Thread{
        @Override
        public void run() {
            while(true) {

                synchronized (lock) {
                    if(cnt > 100) {
                        lock.notifyAll();
                        break;
                    }
                    System.out.println("线程A打印: " + cnt);
                    cnt++;
                    lock.notifyAll();
                    try{
                        lock.wait();
                }catch (InterruptedException ex){}
            }
        }

        }
    }
    static class thread2 extends Thread{
        @Override
        public void run() {
            while(true) {

                synchronized (lock) {
                    if(cnt > 100) break;
                    System.out.println("线程B打印: " + cnt);
                    cnt++;
                    lock.notifyAll();
                    try{
                        lock.wait();
                    }catch (InterruptedException ex){}
                }
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new thread1();
        Thread t2 = new thread2();
        t1.start();t2.start();
        t1.join();t2.join();

    }
}

  • 对象监视器:每个 Java 对象都有一个隐含的监视器(或锁)。当线程进入同步块或方法时,它会获取对象的监视器。
  • notifyAll() :主要作用是唤醒其他线程。唤醒所有等待在该对象监视器上的线程。

notifyAll() 的主要用途是在多线程环境中协调线程的执行。典型的应用场景是生产者-消费者模式或其他需要多个线程合作完成任务的情况。当一个线程完成了某个重要操作,或者满足了某些条件,可以调用 notifyAll() 方法来通知所有等待在该对象上的线程继续执行。

  • wait():使当前线程进入等待状态,并释放对象的监视器;
  • notify(): 唤醒一个等待在该对象监视器上的线程。

方法2 :使用conditiion控制两个线程

两个线程分别负责打印奇数和偶数。
通过 lock 和 condition 控制线程的执行顺序。
使用 while 循环和 condition.await() 方法来等待正确的打印时机。

package org.example;

import jdk.nashorn.internal.ir.ContinueNode;

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

/**
 * @author lhd
 * @version 1.0
 * @date 2024/5/26 22:31
 */
public class TwoThreadR {
    static int cnt = 1;
    static final Lock lock = new ReentrantLock();
    static final Condition condition = lock.newCondition();
    static boolean flag = true;

    static class myRun1 implements Runnable{
        private final int start;


        public myRun1(int start){
            this.start = start;
        }
        public void run(){
            for (int i = start;i <=100;i += 2){
                lock.lock();
                try{
                    while((flag == true && i%2 == 0) || (flag == false && i%2 == 1)){
                        condition.await();
                    }
                    System.out.println("线程"+start+"打印: "+i);
                    flag = !flag;
                    condition.signalAll();

                }catch(InterruptedException e){
                    Thread.currentThread().interrupt();
                }finally {
                    lock.unlock();
                }
            }


        }
    }
    public static void main(String[] args) {
        Thread t1 = new Thread(new myRun1(1)) ;
        Thread t2 = new Thread(new myRun1(2));
        t1.start();
        t2.start();
    }
}

方法3:(待更新 明日更新)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

幼儿园大哥7

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值