多线程题目

3 篇文章 0 订阅

多线程题目

题目描述

有3个线程和1个公共的字符数组。线程1的功能就是向数组输出A,线程2的功能就是向字符输出l,线程3的功能就是向数组输出i。要求按顺序向数组赋值AliAliAli,Ali的个数由线程函数1的参数指定。

代码
import java.util.ArrayList;
import java.util.List;

 /**
 * <p>ClassName: ThreadClass </p>
 * <p>Description: 多线程</p>
 * <p>Author: spring.zhang</p >
 * <p>Date: 2020年4月23日</p>
 */
public class ThreadClass {
	
	public static void main(String[] args) {
		
		final Hander hander = new Hander(3);
		 
		for (int i = 0; i < 3; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					hander.print(Thread.currentThread().getName());
				}
			}, i + "").start();
		}
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(hander.list.toString());
	}

}


class Hander {
	
	private int no;
	
	public Hander(int no) {
		this.no = no ;
	}
	
	private int status = 0;
	
	List<String> list = new ArrayList<String>();
	
	String arr[] = { "A", "l", "i" };
	
	// 将该方法上锁
	public synchronized void print(String threadName) {
		for(int i=0; i<no; i++) {
			int threadIndex = Integer.parseInt(threadName);
			while (threadIndex != status) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			// 添加到数组
			list.add(arr[threadIndex]);
			// 状态转移
			status = (status + 1) % 3;
			this.notifyAll();
		}
	}
	
}
打印输出

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值