这篇文章给大家分享的是有关Java如何创建线程的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
Java创建线程主要有三种方式:继承Thread类创建线程、实现Runnable接口创建线程和实现Callable和Future创建线程。
继承Thread类
public class Thread1 extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(getName() + ": " + i);
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
if (i == 2) {
new Thread1().start();
new Thread1().start();
}
}
}
}
实现Runnable接口
public class Thread2 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) {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
if (i == 2) {
Thread2 thread2 = new Thread2();
new Thread(thread2).start();
new Thread(thread2).start();
}
}
}
}
实现Callable接口
FutureTask类包装Callable对象时,封装了Callable对象的call()方法的返回值。
class Thread3 implements Callable {
@Override
public Integer call() throws Exception {
int i = 0;
for (; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
return i;
}
public static void main(String[] args) {
Thread3 thread3 = new Thread3();
FutureTask<Integer> futureTask = new FutureTask<Integer>(thread3);
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " :" + i);
if (i == 2) {
new Thread(futureTask, "有返回值的线程").start();
}
}
try {
System.out.println("子线程返回值: " + futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
三种方式优缺点
采用实现接口(Runnable和Callable)的方式,线程类还可以继承其他的类。实现接口的线程对象还可以用来创建多个线程,可以实现资源共享。缺点是不能使用this指针来获取线程的名字等。
采用继承Thread类的方式,线程不能继承其他的类,但是Thread类中有getName方法,因为可以直接使用this.getName()来获取当前线程的名字。
感谢各位的阅读!关于“Java如何创建线程”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。