学会定义和使用线程类的生命周期、学会使用线程的同步

感兴趣的小伙伴可以先看看我的这篇文章哦,打开看看,说不定能帮到你一些~~

金陵科技学院软件工程学院软件工程专业

1.执行一个线程,写出线程的执行的生命周期
样例代码:

package com.zhangyufan.thread;

public class TestThreadLifeTime {

	public static void main(String[] args) throws InterruptedException {
		ThreadLifeTime tlf = new ThreadLifeTime();
		Thread thread = new Thread(tlf, "测试生命周期线程");
		System.out.println("new后的状态:" + thread.getState());
		thread.start();
		System.out.println("start后的状态:" + thread.getState());
		Thread.sleep(1000);
		System.out.println("等待时的状态:" + thread.getState());
		Thread.sleep(4000);
		System.out.println("线程执行结束后的状态:" + thread.getState());
	}

}

class ThreadLifeTime implements Runnable {

	@Override
	public void run() {
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + "--结束");
	}

}

运行结果:
在这里插入图片描述
2. 写出一个 3 个人同时发放 50 份广告的程序
要统计每一个人发出的广告数量
实现代码(用于统计数量的方法并不唯一,此处本蒟蒻只写了一种,欢迎各位大佬补充):

package com.zhangyufan.thread;

import java.util.HashMap;
import java.util.Map;

public class TestAd {

	public static void main(String[] args) throws InterruptedException {
		AdThread thread = new AdThread();
		Thread t1 = new Thread(thread, "员工1号");
		Thread t2 = new Thread(thread, "员工2号");
		Thread t3 = new Thread(thread, "员工3号");
		t1.start();
		t2.start();
		t3.start();
		Thread.sleep(4000);
		for (String name : thread.map.keySet()) {
			System.out.println(name + "发了" + thread.map.get(name) + "份广告");
		}
	}
}

class AdThread implements Runnable {
	private int ad = 50;
	Map<String, Integer> map = new HashMap<String, Integer>();

	@Override
	public void run() {
		for (int i = 0; i < 50; i++) {
			send();
		}
	}

	synchronized public void send() {
		if (ad > 0) {
			String name = Thread.currentThread().getName();
			int currentCount = map.get(name) == null ? 1 : map.get(name) + 1;
			map.put(name, currentCount);
			System.out.println(Thread.currentThread().getName() + "发广告,剩余广告数量:" + --ad);
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
	}

}

运行结果:
在这里插入图片描述
在这里插入图片描述

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Spiderman_94

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

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

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

打赏作者

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

抵扣说明:

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

余额充值