Java基础之多线程的三种实现方式
在Java中,通过多线程可以让程序同时执行多个任务,提高程序的并发性。这篇文章将会介绍Java多线程的三种实现方式,包括继承Thread类、实现Runnable接口和实现Callable接口。同时,我们还会附上代码示例进行详细说明。
继承Thread类
第一种实现多线程的方式是继承Thread类。继承Thread类后需要重写run()方法,该方法中包含线程执行的代码。
代码示例:
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
}
}
运行结果:
Thread-0 0
Thread-1 0
Thread-0 1
Thread-1 1
Thread-0 2
Thread-1 2
Thread-0 3
Thread-1 3
Thread-0 4
Thread-1 4
Thread-0 5
Thread-1 5
Thread-0 6
Thread-1 6
Thread-0 7
Thread-1 7
Thread-0 8
Thread-1 8
Thread-0 9
Thread-1 9
实现Runnable接口
第二种实现多线程的方式是实现Runnable接口。实现Runnable接口后需要重写run()方法,同样包含线程执行的代码。需要注意的是,实现Runnable接口的类不是一个线程,需要借助Thread类的start()方法来启动线程。
代码示例:
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}
运行结果:
Thread-0 0
Thread-1 0
Thread-1 1
Thread-0 1
Thread-1 2
Thread-0 2
Thread-1 3
Thread-0 3
Thread-1 4
Thread-0 4
Thread-1 5
Thread-0 5
Thread-1 6
Thread-0 6
Thread-1 7
Thread-0 7
Thread-1 8
Thread-0 8
Thread-1 9
Thread-0 9
实现Callable接口
第三种实现多线程的方式是实现Callable接口。实现Callable接口后需要重写call()方法,和run()方法类似也要写线程执行的代码。在main方法中,需要借助FutureTask类来启动线程,该类可以接受Callable接口的实现类作为参数,同时支持等待线程执行完后获取返回值。
代码示例:
public class MyCallable implements Callable<String> {
@Override
public String call() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
return "Callable done";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable c = new MyCallable();
FutureTask<String> task1 = new FutureTask<>(c);
FutureTask<String> task2 = new FutureTask<>(c);
Thread t1 = new Thread(task1);
Thread t2 = new Thread(task2);
t1.start();
t2.start();
System.out.println(task1.get());
System.out.println(task2.get());
}
}
运行结果:
Thread-0 0
Thread-1 0
Thread-1 1
Thread-0 1
Thread-1 2
Thread-0 2
Thread-1 3
Thread-0 3
Thread-1 4
Thread-0 4
Thread-1 5
Thread-0 5
Thread-1 6
Thread-0 6
Thread-1 7
Thread-0 7
Thread-1 8
Thread-0 8
Thread-1 9
Thread-0 9
Callable done
Callable done
以上就是Java多线程的三种实现方式的详细攻略。在实际开发中,需要根据实际情况选择不同的实现方式。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java基础之多线程的三种实现方式 - Python技术站