多线程

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;
            }
        }
    }
}
原文地址:https://www.cnblogs.com/guoyu1/p/12435857.html