目录
1.线程
2.多线程的应用场景
3.并发和并行
4.多线程的实现方式
1.继承Thread类的方式进行实现
创建类继承Tread类,并重写run方法:
public class MyThread extends Thread {
@Override
public void run() {
//重写run方法
for (int i = 0; i < 100; i++) {
System.out.println(getName() + ":hello world!");
}
}
}
测试线程之间的并发性:
public class Main{
public static void main(String[] args) {
//创建线程
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
//线程取名
t1.setName("线程1");
t2.setName("线程2");
//开启线程
t1.start();
t2.start();
}
}
2.实现Runnable接口的方式进行实现
定义一个类实现Runnable接口,并重写方法:
public class Myrun implements Runnable {
@Override
public void run() {
//重写方法
for (int i = 0; i < 100; i++) {
//获取当前的对象
Thread t = Thread.currentThread();
System.out.println(t.getName() + ":hello world!");
}
}
}
测试线程之间的交互执行的并发性:
public class Myrun implements Runnable {
@Override
public void run() {
//重写方法
for (int i = 0; i < 100; i++) {
//获取当前的对象
Thread t = Thread.currentThread();
System.out.println(t.getName() + ":hello world!");
}
}
}
3.利用Callable接口和Future接口方式实现
创建一个类实现Callable接口,并重写方法:
public class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
//求1到100之间的和
int sum = 0;
for (int i = 0; i <= 100; i++) {
sum += i;
}
return sum;
}
}
主函数:创建线程测试接口中的求和方法。
public class Main{
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建Callable的对象:表示多线程要执行的任务
MyCallable mc = new MyCallable();
//创建一个FutureTask的对象:作用管理多线程运行的结果
FutureTask<Integer> ft = new FutureTask<>(mc);
//创建线程的对象
Thread t1 = new Thread(ft);
//启动线程
t1.start();
//获取多线程运行的结果
System.out.println(ft.get());//5050
}
}