本文主要是介绍技术问答-13 Java线程的实现方式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1. 继承Thread类
package test;import java.util.concurrent.TimeUnit;public class Test extends Thread{public void run() {for(int i=0;i<10;i++){try {
TimeUnit.SECONDS.sleep(2);
System.out.println("线程啊!"+Thread.currentThread().getName());} catch (InterruptedException e) {
e.printStackTrace();}}}public static void main(String[] args) {
Test myThread1 = new Test();
Test myThread2 = new Test();
myThread1.start();
myThread2.start();}}
2.实现Runnable接口
package test;import java.util.concurrent.TimeUnit;public class Test implements Runnable{public void run() {for(int i=0;i<10;i++){try {
TimeUnit.SECONDS.sleep(2);
System.out.println("线程啊!"+Thread.currentThread().getName());} catch (InterruptedException e) {
e.printStackTrace();}}}public static void main(String[] args) {
Thread myThread1 = new Thread(new Test());
Thread myThread2 = new Thread(new Test());
myThread1.start();
myThread2.start();}}
3.实现Callable接口 通过FutureTask创建线程 可以获取线程返回结果
package test;import java.util.concurrent.Callable;import java.util.concurrent.FutureTask;import java.util.concurrent.TimeUnit;public class Test implements Callable<String>{public String call() {try {
TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {
e.printStackTrace();}return "测试Callable";}public static void main(String[] args) {
Test test = new Test();
FutureTask<String> ft = new FutureTask<String>(test);
Thread thread = new Thread(ft);
thread.start();try{
System.out.println(ft.get());}catch(Exception e){
e.printStackTrace();}}}
4.使用ExecutorService
import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;public class Test implements Callable<String> {public String call() {try {
TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {
e.printStackTrace();}return "测试Callable";}public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(1);
Future<String> f = pool.submit(new Test());
pool.shutdown();try {// 有返回值 阻塞等待
System.out.println(f.get());} catch (Exception e) {
e.printStackTrace();}
ExecutorService pool2 = Executors.newFixedThreadPool(1);//不阻塞
pool2.execute(new testR());}}class testR implements Runnable {@Overridepublic void run() {
System.out.println("测试线程!!");}}
这篇关于技术问答-13 Java线程的实现方式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!