创建线程的方法:
1:继承thread类(实现rannable接口),实现run方法
public class Way1 extends Thread{
public static void main(String[] args) {
Way1 thread1 = new Way1();
thread1.start();
Way1 thread2 = new Way1();
thread2.start();
}
@Override
public void run() {
for (int i = 0;i<=10;i++) {
System.out.println("线程" + Thread.currentThread()+"执行中。。。。。。。。");
}
}
}
2:实现runnable接口,重写run方法
public class Way2 implements Runnable{
public static void main(String[] args) {
Thread thread = new Thread(new Way2());
thread.start();
Thread thread1 = new Thread(new Way2());
thread1.start();
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("线程" + Thread.currentThread() + "执行中。。。。。。");
}
}
}
匿名内部类(lambda表达式)
public class Way22 {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("线程" + Thread.currentThread() + "执行中。。。。。。");
}
}
});
thread.start();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("线程" + Thread.currentThread() + "执行中。。。。。。");
}
}
});
thread1.start();
}
}
public class Way222 {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
for (int i = 0;i<10;i++) {
System.out.println("线程" + Thread.currentThread() + "执行中。。。。。");
}
});
thread.start();
Thread thread1 = new Thread(() -> {
for (int i = 0;i<10;i++) {
System.out.println("线程" + Thread.currentThread() + "执行中。。。。。");
}
});
thread1.start();
}
}
3:实现callable接口(继承了runable)
实 现call方法
创建future task对象,创建thread类对象传入future task对象,使用start开启线程
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Way3 implements Callable<String> {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> futureTask = new FutureTask<>(new Way3());
FutureTask<String> futureTask1 = new FutureTask<>(new Way3());
Thread thread = new Thread(futureTask);
Thread thread1 = new Thread(futureTask1);
thread.start();
thread1.start();
String result = futureTask.get();
System.out.println(result);
String result1 = futureTask1.get();
System.out.println(result1);
}
@Override
public String call() throws Exception {
return "线程" + Thread.currentThread() + "执行中。。。。。。";
}
}
4:实现runnable接口,实现run方法,创建executorservice对象,调用execute方法传入实现runnable接口的类的实例化对象即可开启线程。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Way4 implements Runnable{
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new Way4());
executorService.execute(new Way4());
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("线程" + Thread.currentThread() + "执行中。。。。。。");
}
}
}