hbf548

多看源码多读书

0%

Runnable

  • 定义MyRunnable类实现Runnable接口
  • 实现run()方法,编写线程执行体
  • 创建线程对象,调用start()方法启动线程。

注意:
通过实现Runnable方法启动的线程。通过Thread类调用start()方法启动线程,调用当前线程的润方法。===》但是它调用的是Runnable类型的target的run()方法。
image

image

image

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现,调用start方法
public class TestThread implements Runnable{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在写代码==========" + i);
}
}

public static void main(String[] args) {

//创建runnable接口的实现类
TestThread testThread = new TestThread();

//创建线程对象,通过线程对象来开启我们的线程,代理
Thread thread = new Thread(testThread);

thread.start();

//mian线程,主线程
for (int i = 0; i < 2000; i++) {
System.out.println("我在学习======="+i);
}
}
}

结果一样!

因为java中支持单继承,而可以实现多个接口,所以一般用Runnable接口!

image