线程实现
一、线程创建
1.1线程的创建方式
1.1.1Thread class → 继承Thread类(重点)
自定义线程类继承Thread类
重写run()方法,编写线程主体
创建线程对象,调用start()方法启动线程
public class TestThread1 extends Thread{
@Override
public void run(){
for(int i=0; i<50;i++){
System.out.println("线程1------------"+ i);
}
}
public static void main(String[] args) {
TestThread1 task = new TestThread1();
// run相当于同步执行(顺序执行,直接调用类方法)
// task.run();
task.start();//启动线程
for(int i=0; i<50;i++){
System.out.println("主线程------------"+ i);
}
}
}
执行效果:
1.1.2Runnable接口
实现Runnable接口(重点)
自定义线程类继承Runnable接口
重写run()方法,编写线程主体
将线程对象通过【new Thread().start()】方式启动
public class TestThread3 implements Runnable{
private int n;
public TestThread3(int n ){
this.n = n;
}
@Override
public void run() {
for(int i=0; i<50;i++){
System.out.println("线程"+n+":"+ i);
}
}
public static void main(String[] args) {
TestThread3 task1= new TestThread3(1);
TestThread3 task2 = new TestThread3(2);
new Thread(task1).start();
Thread thread = new Thread(task2);
thread.start();
}
}
执行效果:
1.1.3Callable接口
实现Callable接口(初步接触多线程时了解就好)
实现Callable接口,需要返回值类型
重写call()方法,需要抛出异常
创建目标对象
创建线程池服务:ExecutorService service = Executors.newFixedThreadPool(3);
提交执行 :Future result1 = service.submit(taks1);
获取结果:Boolean r1 = result1.get();
关闭服务:service.shutdownNow();
public class TestCallable implements Callable<Boolean> {
private String taskname;
public TestCallable(String taskname) {
this.taskname = taskname;
}
@Override
public Boolean call(){
for (int i = 0; i < 10; i++) {
System.out.println(this.taskname+"执行中:"+i);
}
System.out.println(this.taskname+"执行完成----------------------");
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建三个线程对象
TestCallable taks1 = new TestCallable("线程1");
TestCallable taks2 = new TestCallable("线程2");
TestCallable taks3= new TestCallable("线程3");
//创建线程服务 这里设置了线程池为3
ExecutorService service = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> result1 = service.submit(taks1);
Future<Boolean> result2 = service.submit(taks2);
Future<Boolean> result3 = service.submit(taks3);
//获取结果
Boolean r1 = result1.get();
Boolean r2 = result2.get();
Boolean r3 = result3.get();
System.out.println(r1);
System.out.println(r2);
System.out.println(r3);
//关闭服务
service.shutdownNow();
}
}
执行效果: