线程的创建
线程的创建方式:
1 集成Thread类
Thread类实际上是实现了Runnable接口的一个实例,代表一个线程的实例,启动线程的唯一方
法就是通过 Thread 类的 start()实例方法。它将启动一个新线程,并执行 run()方法
public class TestThread extends Thread {
@Override
public void run() {
int number = 10000;
for (int i = 0; i < number; i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
Integer number = 199;
new TestThread().start();
for (int i = 0; i < number; i++) {
System.out.println("11111111111");
}
}
}
2 实现Runnable接口,重写run方法
public class MyThread implements Runnable{
public void run() {
int number = 100;
for (int i = 0; i <number ; i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread);
thread.start();
int number = 100;
for (int i = 0; i <number; i++) {
System.out.println("111111111111111");
}
}
}
方法三 : Callable、Future 有返回值线程
有返回值的任务必须实现 Callable 接口,类似的,无返回值的任务必须 Runnable 接口。执行
Callable 任务后,可以获取一个 Future 的对象,在该对象上调用 get 就可以获取到 Callable 任务
返回的 Object 了,再结合线程池接口 ExecutorService 就可以实现有返回结果的多线程了
public class CallableThread implements Callable {
@Override
public Object call() throws Exception {
return "hello world";
}
public static void main(String[] args) {
//使用线程池
ExecutorService executorService = Executors.newFixedThreadPool(100);
List<Future> list = new ArrayList<Future>(16);
int num = 16;
for (int i = 0; i <num ; i++) {
Callable c = new CallableThread();
Future f = executorService.submit(c);
list.add(f);
}
executorService.shutdown();
list.forEach(f -> {
try {
System.out.println(f.get().toString());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
}
}