十三、多线程(续)
多线程(续):
实现多线程的三种方法Thread,Runnable,Callable。
Thread方法:
@Override
public void run() {
System.out.println("第"+Thread.currentThread().getName()+"的Thread方法");
}
public static void main(String[] args) {
ThreadDemo01 tr=new ThreadDemo01();
tr.setName("线程一");
tr.start();
ThreadDemo01 tr1=new ThreadDemo01();
tr1.setName("线程二");
tr1.start();
}
Runnable接口:
public class RunnableDemo implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"Runnable方法一");
}
public static void main(String[] args) {
RunnableDemo runnableDemo=new RunnableDemo();
Thread tr=new Thread(runnableDemo);
tr.start();
Thread tr2=new Thread(runnableDemo);
tr2.start();
Thread tr3=new Thread(runnableDemo);
tr3.start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"Runnable方法二");
}
}).start();
}
}
Callable接口:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableDemo implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int i=1;
for (;i<10;i++){
System.out.println(Thread.currentThread().getName()+i);
}
return i;
}
public static void main(String[] args) {
CallableDemo call=new CallableDemo();
FutureTask<Integer> fut=new FutureTask<>(call);
for (int i=1;i<10;i++){
System.out.println(Thread.currentThread().getName()+" 的循环变量i的值"+i);
if(i==2)
{
new Thread(fut,"有返回值的线程").start();
}
}
try
{
System.out.println("子线程的返回值:"+fut.get());
} catch (InterruptedException e)
{
e.printStackTrace();
} catch (ExecutionException e)
{
e.printStackTrace();
}
}
}
三种方法的区别:
-
采用实现 Runnable、Callable 接口的方式创建多线程时,线程类只是实现了 Runnable 接口或 Callable 接口,还可以继承其他类。
-
使用继承 Thread 类的方式创建多线程时,编写简单,如果需要访问当前线程,则无需使用 Thread.currentThread() 方法,直接使用 this 即可获得当前线程。