题目
用“Runnable+内嵌 Thread 引用”方式构造 3 个线程对象,分别输出 2、3、5 的 1-20 倍,指出输出结果中的 30 是那个线程输出的。
代码如下
- package com.liuyanzhao;
- class Run1 implements Runnable {
- int x;
- public Run1(int x) {
- this.x = x;
- }
- public void run() {
- for(int i=1;i<=20;i++) {
- int mul = x*i;
- if(mul == 30) {
- System.out.print(“30(是线程”+Thread.currentThread().getName()+“输出的) “);
- } else {
- System.out.print(mul+” “);
- }
- }
- }
- }
- public class Test1 {
- public static void main(String[] args) {
- Run1 run1 = new Run1(2);
- Run1 run2 = new Run1(3);
- Run1 run3 = new Run1(5);
- Thread t1 = new Thread(run1,“t1”);
- Thread t2 = new Thread(run2, “t2”);
- Thread t3 = new Thread(run3, “t3”);
- t1.start();
- t2.start();
- t3.start();
- }
- }
运行结果:
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