1 继承Thread类
多线程的实现
实现多线程只需要继承Thread类即可,重写run()方法,封装需要被线程执行的代码
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 11; i++) {
System.out.println(i);
}
}
}
public class ThreadTest {
public static void main(String[] args) {
Thread my1 = new MyThread();
Thread my2 = new MyThread();
Thread my3 = new MyThread();
my1.start(); // 启动线程,由JVM调用线程的run()方法
my2.start();
my3.start();
}
}
获取和设置线程名称
使用getName()
方法获取线程名称
@Override
public void run() {
for (int i = 0; i < 11; i++) {
System.out.println(getName() + " " + i);
}
}
使用setName()
方法设置线程名称
my1.setName("HelloWorld");
线程优先级
getPriority()
返回线程优先级
setPriority()
设置线程优先级
- 优先级由低到高为 1-10 , 默认值为 5
- 线程优先级高仅仅表示线程获取CPU时间片的几率高
- 并不一定会等优先级高的线程执行完了才去执行优先级低的线程
public class ThreadTest {
public static void main(String[] args) {
Thread my1 = new MyThread();
Thread my2 = new MyThread();
Thread my3 = new MyThread();
System.out.println(my1.getPriority()); //返回线程优先级
my1.setPriority(10); // 设置线程优先级
my2.setPriority(5);
my3.setPriority(1);
my1.start();
my2.start();
my3.start();
}
}
2 实现Runnable接口
虽然继承Thread类实现多线程非常简单,但是在实际开发中,java单继承这一特性使得我们在需要继承其他类的时候,多线程的实现就要依靠实现Runnable接口
public class MyRunnable implements Runnable {
@override
public void run() { // 同样重写run()方法
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
}
/**
* 创建MyRunnable类的对象
* 创建Thread类的对象,将MyRunnable对象作为构造方法的参数
*/
public class MyRunnableTest {
public static void main(String[] args) {
Runnable r1 = new MyRunnable();
Thread t1 = new Thread(r1, "hello"); // 可以直接设置线程名称
Thread t2 = new Thread(r1, "world");
t1.start();
t2.start();
}
}
方法2总结
- 没有继承Thread类,如果有需求可以继承其他类
- 适合多个相同程序的代码去处理同一个资源的情况,把线程和程序的代码、数据有效分离
3 实现Callable接口
- 重写call()方法
- 好处:有返回值,允许抛异常
4 使用线程池
- 减少创建新线程的时间,重复利用线程池中的线程,降低资源消耗,可有返回值。