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

87 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

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() + "--结束");
     }
 ​
 }

运行结果:

在这里插入图片描述

  1. 写出一个 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();
             }
 ​
         }
     }
 ​
 }

运行结果:

在这里插入图片描述 在这里插入图片描述