多线程就是能充分利用CPU的等待时间,同时进行多个操作,提高效率
并发:在同一时刻,有多个指令在单个CPU上交替执行
并行:在同一时刻,有多个指令在多个CPU上同时执行
继承Thread类
优点:比较简单,可以直接使用Thread类中的方法
缺点:扩展性比较差,不能再继承其他类
thread t1 = new thread();
thread t2 = new thread();
t1.setName("11111");
t2.setName("22");
t1.start();
t2.start();
实现Runnable接口
优点:扩展性强,还可以同时继承其他类
缺点:书写较为复杂,不能直接使用Thread类中的方法
步骤
自定义一个类实现Runable接口
重写run方法
创建此类的对象
创建一个Thread类的对象,并开启线程
public class Test {
public static void main(String[] args) {
thread t = new thread();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.setName("线程1");
t2.setName("线程2");
t1.start();
t2.start();
}
}
public class thread implements Runnable{
public void run() {
for (int i = 0; i < 100; i++) {
Thread t = Thread.currentThread();
System.out.println(t.getName() + "hello!");
}
}
}
实现Callable接口
优点:扩展性强,还可以同时继承其他类
缺点:书写较为复杂,不能直接使用Thread类中的方法
特点:可以获取到多线程运行的结果
步骤:
创建一个类实现Callable接口
重写call(有返回值,为多线程运行的结果)
创建此类的对象(表示多线程要执行的任务)
创建FutureTask的对象(管理多线程运行的结果)
创建Thread类的对象,并启动(表示线程)
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
thread t = new thread();
FutureTask<Integer> f = new FutureTask<>(t);
Thread t1 = new Thread(f);
t1.start();
Integer i = f.get();
System.out.println(i);
}
}
public class thread implements Callable {
@Override
public Integer call() throws Exception {
int s = 0;
for (int i = 0; i <= 100 ; i++) {
s += i;
}
return s;
}
}