多线程有3种实现方式
1:继承Threads
2:实现接口Runable
3:实现接口Callable
其中实现接口Callable是在jdk1.5之后才有,对比Runable,Callable方法有返回结果
1:
public class Test extends Thread{
//因为static是静态变量,所以可以实现多个线程一起执行0-100,不重复,若没有static则每个线程都执行一次1-100
private static int i=0;
private String name;
public Test18(String name) {
this.name=name;
}
@Override
public synchronized void run() {
for(;i<100;i++) {
System.out.println(name+"_____"+i);
}
}
public static void main(String[] args) {
Thread thread1=new Test("name1");
Thread thread2=new Test("name2");
thread1.start();
thread2.start();
}
}
2.
public class Test implements Runnable{
private int i=0;
private String name;
public Test18(String name) {
this.name=name;
}
@Override
public synchronized void run() {
for(;i<100;i++) {
System.out.println(name+"_____"+i);
}
}
public static void main(String[] args) {
Thread thread1=new Thread(new Test("name1"));
Thread thread2=new Thread(new Test("name2"));
thread1.start();
thread2.start();
}
}
3.
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Test implements Callable<Integer>{
private static int i=0;
private String name;
public Test18(String name) {
this.name=name;
}
@Override
public Integer call() throws Exception {
for(;i<100;i++) {
System.out.println(name+"_____"+i);
}
return i;
}
public static void main(String[] args) {
//1.执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。
FutureTask<Integer> result = new FutureTask<>(new Test("name1"));
FutureTask<Integer> result1 = new FutureTask<>(new Test("name2"));
Thread thread1=new Thread(result);
Thread thread2=new Thread(result1);
thread1.start();
thread2.start();
}
}
注:如果使用static来控制计数的话是线程不安全的,很容易出现错误,建议不要使用
以上的方法实现都是用new Thread方法来新建一个线程然后实现的,还有一中方法是使用新建ExecutorService(创建线程池)来实现的。例子如下:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test18 implements Callable<Integer>{
private static int i=0;
private String name;
private ExecutorService eService = Executors.newFixedThreadPool(5);
public Test18(String name) {
this.name=name;
}
@Override
public Integer call() throws Exception {
for(;i<100;i++) {
System.out.println(name+"_____"+i);
}
return i;
}
public static void main(String[] args) {
List<Callable<Integer>> list=new ArrayList<Callable<Integer>>();
list.add(new Test18("name1"));
list.add(new Test18("name2"));
Test18 t=new Test18("name3");
try {
t.eService.invokeAll(list);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}