多种创建线程的方式
java标准库提供了一个
Thread类
帮助我们实现线程通过Thread 与
Runnable
/ lambda 方式创建的线程本质上没什么区别核心都是依靠thread类 ,但是细节上(站在耦合性的角度) 在使用Runnable和 Lambda创建的线程在run中没有涉及到Thread相关的内容, 这就意味着很容易把这些逻辑从线程中剥离出来,去搭配其他并发编程的方式来执行,也可能会容易改成不并发的方式去执行
多线程的方式:
Thread类 与 Runnable接口
public class ThreadTest3 {
static class MyThread extends Thread {
@Override
public void run() {
System.out.println("hello");
}
}
static class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("hello");
}
}
public static void main(String[] args) {
//1定义一个类继承Thread
Thread t = new MyThread();
t.start();
//2定义匿名内部类
Thread t1 = new Thread() {
@Override
public void run() {
System.out.println("hello");
}
};
t1.start();
//3 lambda表达式
Thread t2 = new Thread(() -> {
System.out.println("hello");
});
t2.start();
//4定义一个类继续Runnable接口,但注意要将runnable对象关联到Thread对象上
Runnable r1 = new MyRunnable();
Thread t3 = new Thread(r1);
t3.start();
//5匿名内部类继续Runnable接口
Runnable r2 = new Runnable() {
@Override
public void run() {
System.out.println("hello");
}
};
Thread t4 = new Thread(r2);
t4.start();
//6对Runnable进行Lambda表达式
Runnable r3 = () -> {
System.out.println("hello");
};
Thread t5 = new Thread(r3);
t5.start();
}
}
使用Callable/Future/FutureTask创建线程
- FutureTask是继承于Future的 所以使用FutureTask和Callable可以创建一个带返回值得多线程结果
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Demo {
static class MyThread implements Callable<String> {
private int ticket = 10;
@Override
public String call() throws Exception {
while (this.ticket > 0) {
System.out.println("余票为:" + this.ticket--);
}
return "票空";
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> task = new FutureTask<>(new MyThread());
Thread thread = new Thread(task);
Thread thread1 = new Thread(task);
thread.start();
thread1.start();
//get方法会阻塞 直到task运行结束
System.out.println(task.get());
}
}
多线程的优势-增加运行速度
public class ThreadTest2 {
private static long count = 10_0000_0000;
public static void main(String[] args) {
Danxianc();
Duoxianc();
}
private static void Danxianc() {
long beg = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
int a;
a = i;
}
for (int i = 0; i < count; i++) {
int b;
b = i;
}
System.out.println(System.currentTimeMillis() - beg + "ms");
}
private static void Duoxianc() {
long beg = System.currentTimeMillis();
Thread thread = new Thread() {
@Override
public void run() {
for (int i = 0; i < count; i++) {
int a;
a = i;
}
}
};
Thread thread1 = new Thread() {
@Override
public void run() {
for (int i = 0; i < count; i++) {
int b;
b = i;
}
}
};
thread.start();
thread1.start();
//让方法这个线程等待,等thread 和thread1这两线程跑完自己再执行
try {
thread.join();
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() - beg + "ms");
}
}
运行结果:
1753ms
1044ms