Java面试题(2) 两个线程,交替打印100次A和B

news2024/11/23 19:03:16

目录

    • 一、实现方式一
      • 实现思路:
      • 代码实现:
      • 执行结果:
    • 二、实现方式二
      • 实现思路:
      • 代码实现:
      • 执行结果:
    • 三、思考

一、实现方式一

实现思路:

代码实现:

ThreadTest.java

package com.demo.example;

public class ThreadTest {

    public static void main(String[] args) {
        MyThread threadA = new MyThread();
        MyThread threadB = new MyThread();

        threadA.setThread(threadB);
        threadA.setKey("A");
        threadB.setThread(threadA);
        threadB.setKey("B");

        threadA.start();
        threadB.start();
    }

}

class MyThread extends Thread {

    private final Object lock = new Object();
    private MyThread thread;
    private String key;

    public void setThread(MyThread thread) {
        this.thread = thread;
    }
    public void setKey(String key) {
        this.key = key;
    }
    public void getLock() {
        synchronized (lock) {
            try {
                lock.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public void releaseLock() {
        synchronized (lock) {
            lock.notify();
        }
    }

    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            System.out.println(Thread.currentThread().getName() + ", " + key + ",count: " + (i + 1));
            thread.releaseLock();
            if (i < 49) {
                this.getLock();
            }
        }
    }
}

执行结果:

Thread-0, A,count: 1
Thread-1, B,count: 1
Thread-0, A,count: 2
Thread-1, B,count: 2
Thread-0, A,count: 3
Thread-1, B,count: 3
Thread-0, A,count: 4
Thread-1, B,count: 4
Thread-0, A,count: 5
Thread-1, B,count: 5
Thread-0, A,count: 6
Thread-1, B,count: 6
Thread-0, A,count: 7
Thread-1, B,count: 7
Thread-0, A,count: 8
Thread-1, B,count: 8
Thread-0, A,count: 9
Thread-1, B,count: 9
Thread-0, A,count: 10
Thread-1, B,count: 10
Thread-0, A,count: 11
Thread-1, B,count: 11
Thread-0, A,count: 12
Thread-1, B,count: 12
Thread-0, A,count: 13
Thread-1, B,count: 13
Thread-0, A,count: 14
Thread-1, B,count: 14
Thread-0, A,count: 15
Thread-1, B,count: 15
Thread-0, A,count: 16
Thread-1, B,count: 16
Thread-0, A,count: 17
Thread-1, B,count: 17
Thread-0, A,count: 18
Thread-1, B,count: 18
Thread-0, A,count: 19
Thread-1, B,count: 19
Thread-0, A,count: 20
Thread-1, B,count: 20
Thread-0, A,count: 21
Thread-1, B,count: 21
Thread-0, A,count: 22
Thread-1, B,count: 22
Thread-0, A,count: 23
Thread-1, B,count: 23
Thread-0, A,count: 24
Thread-1, B,count: 24
Thread-0, A,count: 25
Thread-1, B,count: 25
Thread-0, A,count: 26
Thread-1, B,count: 26
Thread-0, A,count: 27
Thread-1, B,count: 27
Thread-0, A,count: 28
Thread-1, B,count: 28
Thread-0, A,count: 29
Thread-1, B,count: 29
Thread-0, A,count: 30
Thread-1, B,count: 30
Thread-0, A,count: 31
Thread-1, B,count: 31
Thread-0, A,count: 32
Thread-1, B,count: 32
Thread-0, A,count: 33
Thread-1, B,count: 33
Thread-0, A,count: 34
Thread-1, B,count: 34
Thread-0, A,count: 35
Thread-1, B,count: 35
Thread-0, A,count: 36
Thread-1, B,count: 36
Thread-0, A,count: 37
Thread-1, B,count: 37
Thread-0, A,count: 38
Thread-1, B,count: 38
Thread-0, A,count: 39
Thread-1, B,count: 39
Thread-0, A,count: 40
Thread-1, B,count: 40
Thread-0, A,count: 41
Thread-1, B,count: 41
Thread-0, A,count: 42
Thread-1, B,count: 42
Thread-0, A,count: 43
Thread-1, B,count: 43
Thread-0, A,count: 44
Thread-1, B,count: 44
Thread-0, A,count: 45
Thread-1, B,count: 45
Thread-0, A,count: 46
Thread-1, B,count: 46
Thread-0, A,count: 47
Thread-1, B,count: 47
Thread-0, A,count: 48
Thread-1, B,count: 48
Thread-0, A,count: 49
Thread-1, B,count: 49
Thread-0, A,count: 50
Thread-1, B,count: 50

二、实现方式二

实现思路:

代码实现:

ThreadTest.java

package com.demo.example;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadTest {

    public static void main(String[] args) {
        // 写法一:显示创建Thread
        Runnable runnable = new AbThread();
        Thread threadA = new Thread(runnable);
        Thread threadB = new Thread(runnable);
        threadA.start();
        threadB.start();
        // 写法二:使用线程池
//        ExecutorService executorService = Executors.newCachedThreadPool();
//        executorService.execute(runnable);
//        executorService.execute(runnable);
    }

}

class AbThread implements Runnable {

    char[] content = {'A', 'B'};
    int count = 0;

    @Override
    public void run() {
        synchronized (this) {
            try {
                while(count < 100) {
                    System.out.println(Thread.currentThread().getName() + ", " + content[count % 2] + ",count: " + (++count));
                    notify();
                    if (count < 100) {
                        wait();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

执行结果:

Thread-0, A,count: 1
Thread-1, B,count: 2
Thread-0, A,count: 3
Thread-1, B,count: 4
Thread-0, A,count: 5
Thread-1, B,count: 6
Thread-0, A,count: 7
Thread-1, B,count: 8
Thread-0, A,count: 9
Thread-1, B,count: 10
Thread-0, A,count: 11
Thread-1, B,count: 12
Thread-0, A,count: 13
Thread-1, B,count: 14
Thread-0, A,count: 15
Thread-1, B,count: 16
Thread-0, A,count: 17
Thread-1, B,count: 18
Thread-0, A,count: 19
Thread-1, B,count: 20
Thread-0, A,count: 21
Thread-1, B,count: 22
Thread-0, A,count: 23
Thread-1, B,count: 24
Thread-0, A,count: 25
Thread-1, B,count: 26
Thread-0, A,count: 27
Thread-1, B,count: 28
Thread-0, A,count: 29
Thread-1, B,count: 30
Thread-0, A,count: 31
Thread-1, B,count: 32
Thread-0, A,count: 33
Thread-1, B,count: 34
Thread-0, A,count: 35
Thread-1, B,count: 36
Thread-0, A,count: 37
Thread-1, B,count: 38
Thread-0, A,count: 39
Thread-1, B,count: 40
Thread-0, A,count: 41
Thread-1, B,count: 42
Thread-0, A,count: 43
Thread-1, B,count: 44
Thread-0, A,count: 45
Thread-1, B,count: 46
Thread-0, A,count: 47
Thread-1, B,count: 48
Thread-0, A,count: 49
Thread-1, B,count: 50
Thread-0, A,count: 51
Thread-1, B,count: 52
Thread-0, A,count: 53
Thread-1, B,count: 54
Thread-0, A,count: 55
Thread-1, B,count: 56
Thread-0, A,count: 57
Thread-1, B,count: 58
Thread-0, A,count: 59
Thread-1, B,count: 60
Thread-0, A,count: 61
Thread-1, B,count: 62
Thread-0, A,count: 63
Thread-1, B,count: 64
Thread-0, A,count: 65
Thread-1, B,count: 66
Thread-0, A,count: 67
Thread-1, B,count: 68
Thread-0, A,count: 69
Thread-1, B,count: 70
Thread-0, A,count: 71
Thread-1, B,count: 72
Thread-0, A,count: 73
Thread-1, B,count: 74
Thread-0, A,count: 75
Thread-1, B,count: 76
Thread-0, A,count: 77
Thread-1, B,count: 78
Thread-0, A,count: 79
Thread-1, B,count: 80
Thread-0, A,count: 81
Thread-1, B,count: 82
Thread-0, A,count: 83
Thread-1, B,count: 84
Thread-0, A,count: 85
Thread-1, B,count: 86
Thread-0, A,count: 87
Thread-1, B,count: 88
Thread-0, A,count: 89
Thread-1, B,count: 90
Thread-0, A,count: 91
Thread-1, B,count: 92
Thread-0, A,count: 93
Thread-1, B,count: 94
Thread-0, A,count: 95
Thread-1, B,count: 96
Thread-0, A,count: 97
Thread-1, B,count: 98
Thread-0, A,count: 99
Thread-1, B,count: 100

三、思考

如果是三个线程,交替打印100次ABC,怎么实现?





参考地址:

1.两个线程交替打印100次AB,https://blog.csdn.net/qq_34707456/article/details/103027820

2.两个线程交替打印1-100的奇数和偶数,https://blog.csdn.net/bobo1356/article/details/103408137

3.线程交替输出0-100,https://blog.csdn.net/zhangxiao123qqq/article/details/112842059

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/914108.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Elasticsearch算分优化方案之rescore_query

简介 今天来说一说Elasticsearch 的重新评分&#xff0c;即在检索出来一次结果的基础上在进行检索提升数据排序效果&#xff0c;但是仅对查询或者post_filter阶段返回的前多少条进行二次查询。在每个分片上进行二次检索的文档数量时可以通过window_size 控制的&#xff0c;该参…

PHP8中自定义函数-PHP8知识详解

1、什么是函数&#xff1f; 函数&#xff0c;在英文中的单词是function&#xff0c;这个词语有功能的意思&#xff0c;也就是说&#xff0c;使用函数就是在编程的过程中&#xff0c;实现一定的功能。即函数就是实现一定功能的一段特定代码。 在前面的教学中&#xff0c;我们已…

甜椒叶病害识别(Python代码,pyTorch框架,深度卷积网络模型,很容易替换为其它模型,带有GUI识别界面)

代码运行要求&#xff1a;Torch>1.13.1即可 1.数据集介绍&#xff1a; 第一个文件夹是细菌斑叶&#xff08;3460张&#xff09; 第二个文件夹是 健康&#xff08;4024张&#xff09; 2.整个文件夹 data文件夹存放的是未被划分训练集和测试集的原始照片 picture文件夹存放的…

系统架构:数据库

文章目录 数据库设计关系代数规范化理论求候选键特殊函数依赖Armstrong公理 数据库设计 步骤产出说明1.根据数据要求和处理要求进行需求分析数据流图、数据字典、需求说明书等分析数据流向、数据详细含义等&#xff0c;分析具体需求2.对现实世界进行抽象&#xff0c;进行概念结…

DBeaver 23.1.4发布

导读DBeaver 23.1.4发布,修复和添加了不少功能。 SQL 编辑器 修复了表别名生成问题&#xff08;重复别名问题&#xff09;自动建议现在尊重 “空行是查询分隔符 “选项在某些情况下大大提高了自动建议计算性能修复了别名补全问题&#xff08;冗余空格问题&#xff09;修复了无…

超参数的选择-手工搜索、网格搜索、随机搜索、贝叶斯搜索

超参数&#xff1a;超参数是在建立模型时用于控制算法行为的参数。这些参数不能从常规训练过程中获得。在对模型进行训练之前&#xff0c;需要对它们进行赋值。 超参数与模型的参数不同。模型参数(如神经网络的权重)是在训练过程中学习得到的,而超参数(如学习率、隐藏层数量)需…

2023-8-22 模拟队列

题目链接&#xff1a;模拟队列 #include <iostream>using namespace std;const int N 100010;int m; int q[N], hh, tt -1;int main() {cin >> m;while(m--){string op;int x;cin >> op;if(op "push"){cin >> x;q[tt] x;}else if(op …

原型链继承的缺点

记录一下原型链继承的缺点&#xff1a; 第一点是实例共享属性的问题&#xff0c;如果实例改变了继承的引用类型属性&#xff0c;那么其他实例属性也会被改变 第二点是实例对象的 constructor 属性不正确。child 的 constructor 属性并未指向它自己的构造函数 继承代码如下 …

【水平垂直居中布局】CSS实现水平垂直居中的5种方法(附源码)

文章目录 写在前面涉及知识点1、子绝对定位父相对定位&#xff0c;子节点设置位移实现1.1效果1.2实现源码 2、子绝对定位父相对定位&#xff0c;子节点设置上下边距2.1 效果2.2 实现源码 3、利用flex布局实现3.1 效果3.2 实现源码 4、利用行高和文本水平居中设置4.1 效果4.2 实…

Python代码实现天天酷跑小游戏

前言 最近几天多给大家分享分享一些用Python代码&#xff0c;写出来的小游戏吧 今天分享的游戏是 天天酷跑 大概的效果是这样的&#xff0c;动图没展示出来&#xff0c;大家将就看一下吧 【源码的话 文末名片可以获取 】 实现代码 定义 import pygame,sys import random游…

win11查看文件/文件夹所使用的程序

CtrlShiftEsc 打开任务管理器 打开资源管理器 搜索文件名 右击结束进程

【力扣】374、猜数字大小

猜数字游戏的规则如下&#xff1a; 每轮游戏&#xff0c;我都会从 1 到 n 随机选择一个数字。 请你猜选出的是哪个数字。 如果你猜错了&#xff0c;我会告诉你&#xff0c;你猜测的数字比我选出的数字是大了还是小了。 你可以通过调用一个预先定义好的接口 int guess(int num)…

第七章,文章界面

7.1添加个人专栏 <template><div class="blog-container"><div class="blog-pages"><!-- 用于渲染『文章列表』和『文章内容』 --><router-view/><div class="col-md-3 main-col pull-left"><div cla…

STL list基本用法

目录 list的使用构造函数和赋值重载迭代器(最重要)容量相关插入删除元素操作reversesortuniqueremovesplice list的底层实际是双向链表结构 list的使用 构造函数和赋值重载 构造函数说明list()无参构造list (size_type n, const value_type& val value_type())构造的li…

docker 部署服务

1、使用mysql:5.6和 owncloud 镜像&#xff0c;构建一个个人网盘。 [rootbogon ~]# docker pull mysql:5.6 [rootbogon ~]# docker pull owncloud [rootbogon ~]# docker run -itd --name mysql --env MYSQL_ROOT_PASSWORD123456 mysql:5.6 [rootbogon ~]# docker run -itd -…

SeLinux权限说明及问题解决

一、SELinux文件访问安全策略和app权限配置 在android6.0以后的版本&#xff0c;google采用了SELinux的文件访问安全策略&#xff0c;想比较以前&#xff0c;绝对提高了文件的安全&#xff0c;不像以前那样&#xff0c; 对文件访问可以是无条件的。本篇文章就分享下常用的一些…

走进大模型

1、应用大模型 AIGC 是基于大模型的&#xff0c;而大模型的基础是深度学习。上一篇文章对深度学习进行了初步介绍&#xff0c;首先是深度学习的神经元起源&#xff0c;引发了基于线性函数的模拟&#xff0c;又因为线性函数无法习得逻辑异或&#xff0c;因此引入了非线性的激活…

Linux系统常用指令

目录 1.帮助指令 2.文件目录指令* 3.查找指令 4.时间日期指令 5.压缩和解压 1.帮助指令 ctrl c 取消命令&#xff0c;并且换行&#xff08;清空换行&#xff09;作用&#xff0c;单独清空为crtl u tab换行键 补全命令和文件名&#xff0c;快速按两下可以显示备选选项 …

kafka-python 消费者消费不到消息

排除步骤1&#xff1a; 使用group_id”consumer_group_id_001“ 和 auto_offset_reset"earliest" from kafka import KafkaConsumerconsumer KafkaConsumer(bootstrap_servers["dev-kafka01.test.xxx.cloud:9092"],enable_auto_commitTrue, auto_commit…

arm: day8

1.中断实验&#xff1a;按键控制led灯 流程&#xff1a; key.h /*************************************************************************> File Name: include/key.h> Created Time: 2023年08月21日 星期一 17时03分20秒***************************************…