用“Runnable+内嵌Thread引用”方式构造3个线程对象,分别输出2、3、5的1-20倍,指出输出结果中的30是那个线程输出的

avatar 2017年05月20日14:45:32 1 2688 views
博主分享免费Java教学视频,B站账号:Java刘哥 ,长期提供技术问题解决、项目定制:本站商品点此
题目

用“Runnable+内嵌Thread引用”方式构造3个线程对象,分别输出2、3、5的1-20倍,指出输出结果中的30是那个线程输出的。

代码如下
  1. package com.liuyanzhao;
  2. class Run1 implements Runnable {
  3.     int x;
  4.     public Run1(int x) {
  5.         this.x = x;
  6.     }
  7.     public void run() {
  8.         for(int i=1;i<=20;i++) {
  9.             int mul = x*i;
  10.             if(mul == 30) {
  11.                 System.out.print("30(是线程"+Thread.currentThread().getName()+"输出的) ");
  12.             } else {
  13.                 System.out.print(mul+" ");
  14.             }
  15.         }
  16.     }
  17. }
  18. public class Test1 {
  19.     public static void main(String[] args) {
  20.         Run1 run1 = new Run1(2);
  21.         Run1 run2 = new Run1(3);
  22.         Run1 run3 = new Run1(5);
  23.         Thread t1 = new Thread(run1,"t1");
  24.         Thread t2 = new Thread(run2, "t2");
  25.         Thread t3 = new Thread(run3, "t3");
  26.         t1.start();
  27.         t2.start();
  28.         t3.start();
  29.     }
  30. }

运行结果:

2 5 10 15 20 3 25 4 30(是线程t3输出的) 6 35 6 40 9 45 8 50 12 15 18 21 24 27 30(是线程t2输出的) 33 36 55 60 65 10 12 14 16 18 70 75 80 85 90 95 100 39 20 22 24 26 28 30(是线程t1输出的) 32 34 36 38 40 42 45 48 51 54 57 60



本文地址:https://liuyanzhao.com/4315.html

转载请注明
  • 微信
  • 交流学习,服务定制
  • weinxin
  • 个人淘宝
  • 店铺名:言曌博客咨询部

  • (部分商品未及时上架淘宝)

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0