Java之多线程(实现Runnable接口)

时间:2021-06-06 15:43:34

 

 1 package test_demo.ThreadsDemo;
2
3 public class TestRunnable {
4 public static void main(String[] args) {
5 // 实例化线程 Thread(Runnable threadOb,String threadName);
6 Thread thread1 = new Thread(new RunnableObject("Thread-1#"));
7 Thread thread2 = new Thread(new RunnableObject("Thread-2@"));
8 // 启动线程
9 thread1.start();
10 thread2.start();
11 }
12 }
13
14 /**
15 * 多线程:通过Runnable接口实现
16 * 1、实现Runnable接口;
17 * 2、重新Run方法;
18 */
19 class RunnableObject implements Runnable {
20 private String threadName;
21
22 public RunnableObject(String name) {
23 threadName = name;
24 System.out.println("线程创建:" + name);
25 }
26
27 @Override
28 public void run() {
29 for (int i = 0; i < 50; i++) {
30 System.out.println(this.threadName + ": " + i);
31 }
32 }
33 }