多线程创建方式一:继承Tread类
package com.kemoon.www;
public class Test extends Thread{
// 重写run方法
public void run()
{
for (int i = 0; i < 20; i++) {
System.out.println("子线程"+i);
}
}
public static void main(String[] args) {
Test test = new Test();
test.start();
for (int i = 0; i < 20; i++) {
System.out.println("main Thread"+i);
}
}
}
多线程创建方式二:实现runable接口
package com.kemoon.www;
public class Test implements Runnable{
// 实现run方法
public void run()
{
for (int i = 0; i < 20; i++) {
System.out.println("子线程"+i);
}
}
public static void main(String[] args) {
Test test = new Test();
new Thread(test).start();
for (int i = 0; i < 2000; i++) {
System.out.println("main Thread"+i);
}
}
}
多线程创建方式三:实现callable接口
package com.kemoon.www;
import java.util.concurrent.*;
/*
线程创建方式: 实现callable接口
1.可以定义返回值
2.可以抛出异常
*/
public class TestCallable implements Callable<Boolean> {
private String name;
public TestCallable(String name){
this.name=name;
}
// 执行体
public Boolean call(){
for (int i = 0; i < 20; i++) {
System.out.println(this.name);
}
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable("t1");
TestCallable t2 = new TestCallable("t2");
TestCallable t3 = new TestCallable("t3");
// 创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
// 提交执行
Future<Boolean> r1 = ser.submit(t1);
Future<Boolean> r2 = ser.submit(t2);
Future<Boolean> r3 = ser.submit(t3);
// 获取结果
boolean rs1=r1.get();
boolean rs2=r2.get();
boolean rs3=r3.get();
ser.shutdownNow();
}
}
创建线程池
package com.kemoon.www;
public class TestPool{
public static void main(String[] args){
// 创建服务,创建线程池
ExecutorService service = Executors.newFixedThreadPool(10);
// 执行
service.execute(new Test());
service.execute(new Test());
service.execute(new Test());
service.execute(new Test());
// 关闭链接
service.shutdown();
}
}
class Test implements Runnable{
// 实现run方法
public void run()
{
System.out.println("线程"+i);
}
}