Java线程的学习
线程的好处
1、有效的占用了cpu的空闲时间,从一定程度上提高了效率
2、提高了用户的体验性
3、将一个复杂的进程拆分成若干个小的线程,提高代码的分离性和维护性线程的实现
继承Theral类
* 继承Theral
* 重写run()方法,run()就是线程的执行的逻辑体
* main()函数里,创建一个Theral对象
* 调用start()方法,开始一个新线程代码:
线程类
1 | public class MyThread extends Thread{ |
测试类
1 | public class ThreadTest { |
synchronized代码块来完善一下
实现Runnable接口
- 创建实现Runnable接口的类
- 重写run()方法
- 通过创建Theral对象去调用接口
代码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22public class XianCheng implements Runnable{
private String name;
public XianCheng(String name) {
super();
this.name = name;
}
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println(name+"下载了"+i+"%");
}
}
}
public static void main(String[] args) {
Thread t= new Thread(new XianCheng("肖生客的救赎"));
t.start();
Thread t2= new Thread(new XianCheng("当幸福来敲门"));
t2.start();
}
}