Java中常见线程方法的介绍

本文通过生动的比喻和代码实例,详细解释了线程同步与异步的概念。使用卫生间和班级舞蹈表演的例子,形象地说明了线程同步与异步的区别。并通过Java代码演示了如何实现线程的同步和异步执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程同时进行,为线程异步。 线程一个执行完结接着另一个线程执行叫做线程同步。

就想家里只有一个卫生间一样,不能两个人同时拉屎吧,把门锁好一个个来。  此时为线程同步。

班级表演舞蹈,同学们一起唱一起跳,叫做线程异步。

 

 

demo  

actor 男演员和女演员 分别登台演出

package com.wenzewen.thread.demo.threadandrunnable;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: jhon
 * @Date: 2019/4/20 on 8:18
 * @description: 线程 Thead 和线程 runnerable
 */
public class Actor extends Thread {

  @Override
  public void run() {

    boolean keepRunning = true;
    int count = 0;
    while (keepRunning) {
      System.out.println(getName() + "登台演出");
      System.out.println(getName() + "登台演出次数+" + (++count));
      if (count == 100) {
        keepRunning = false;
      }
      if (count % 10 == 0) {
        try {
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      System.out.println(getName() + "的演出结束了");
    }
  }

  static class Actress implements Runnable {

    @Override
    public void run() {
      boolean keepRunning = true;
      int count = 0;
      while (keepRunning) {
        System.out.println(Thread.currentThread().getName() + "登台演出");
        System.out.println(Thread.currentThread().getName() + "登台演出次数+" + (++count));
        if (count == 100) {
          keepRunning = false;
        }
        if (count % 10 == 0) {
          try {
            Thread.sleep(2000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        System.out.println(Thread.currentThread().getName() + "的演出结束了");
      }
    }
  }


  public static void main(String[] args) {
    Thread actor = new Actor();
    actor.setName("Mr.thread");
    actor.start();

    Actress actress1 = new Actress();
    Thread actress = new Thread(actress1, "Ms.runnerable");
    actress.start();

  }
}

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值