多线程

1、题目描述:

https://www.nowcoder.com/practice/cd99fbc6154d4074b4da0e74224a1582?tpId=37&tqId=21272&tPage=3&rp=&ru=%2Fta%2Fhuawei&qru=%2Fta%2Fhuawei%2Fquestion-ranking

2、思路:

  创建四个线程,第一个线程在char[ ]数组的0,4,8,12........位置上添加‘A’字符,第二个线程在char[ ]数组的1,5,9.......位置上添加‘B’字符,依次类推。

  线程的共享变量是char[ ]。

3、代码:

复制代码
import sun.awt.windows.ThemeReader;

import java.math.BigDecimal;
import java.util.Scanner;


public class test1 {

    public static char[] cs = new char[1032];

    public static void main(String[] args) {
        char ch = 'A';
        //创建线程
        for (int i = 0; i < 4; i++) {
            myTread myTread = new myTread(i, ch++);
            Thread thread = new Thread(myTread);
            thread.start();
        }
        //打印十次abcd
        Scanner scan = new Scanner(System.in);
        while (scan.hasNext()) {
            int num = scan.nextInt();
            System.out.println(new String(cs).substring(0, num * 4));
        }
    }

    static class myTread implements Runnable {
        private int index;
        private char ch;

        public myTread(int index, char ch) {
            this.index = index;
            this.ch = ch;
        }

        @Override
        public void run() {
            while (this.index < cs.length) {
                cs[this.index] = this.ch;
                this.index += 4;
            }
        }
    }
}
复制代码

 

posted @   guoyu1  阅读(101)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示