java是多线程的,使用多线程有三种方法:继承thread类、实现runnable接口和使用callable和future创建线程。
继承thread类 (推荐学习:java课程 )
实现方式很简单,只需要创建一个类去继承thread类然后重写run方法,在main方法中调用该类实例对象的start方法即可实现多线程并发。代码:
public class mythread extends thread { @override public void run(){ super.run(); system.out.println("执行子线程..."); }}
测试用例:
public class test { public static void main(string[] args) { mythread mythread = new mythread(); mythread.start(); system.out.println("主线程..."); }}
运行结果:
实现runnable接口
这种方式的实现也很简单,就是把继承thread类改为实现runnable接口。代码如下:
public class myrunnable implements runnable { @override public void run() { system.out.println("执行子线程..."); }}
测试用例:
public class test { public static void main(string[] args) { runnable runnable = new myrunnable(); thread thread = new thread(runnable); thread.start(); system.out.println("主线程运行结束!"); }}
运行结果:
使用callable和future创建线程
上面的两种方式都有这两个问题:
无法获取子线程的返回值
run方法不可以抛出异常
为了解决这两个问题,我们就需要用到callable这个接口了。说到接口,上面的runnable接口实现类实例是作为thread类的构造函数的参数传入的,之后通过thread的start执行run方法中的内容。但是callable并不是runnable的子接口,是个全新的接口,它的实例不能直接传入给thread构造,所以需要另一个接口来转换一下。
以这里面其实就是要比上一个方法再多一个转换过程,最终一样是通过thread的start来创建新线程。有了这个思路,代码就很容易理解了:
import java.util.concurrent.callable;public class mycallable implements callable { int i = 0; @override public object call() throws exception { system.out.println(thread.currentthread().getname()+" i的值:"+ i); return i++; //call方法可以有返回值 }}
测试:
import java.util.concurrent.callable;import java.util.concurrent.futuretask;public class test { public static void main(string[] args) { callable callable = new mycallable(); for (int i = 0; i < 10; i++) { futuretask task = new futuretask(callable); new thread(task,"子线程"+ i).start(); try { //获取子线程的返回值 system.out.println("子线程返回值:"+task.get() + "\n"); } catch (exception e) { e.printstacktrace(); } } }}
执行结果(部分):
以上就是java是多线程的吗的详细内容。