创建线程
- 继承Thread类 重新 run方法
public class CreateTread1 extends Thread{
@Override
public void run() {
int i=0;
while (i<10000){
System.out.println(i++);
}
}
}
实现类
public class CreateThread2 {
public static void main(String[] args) {
Thread thread = new CreateTread1();
thread.start();
}
}
- 实现Runnable接口,重写run方法,根据实例创建thread对象,thread.start()开启
public class CreateTread1 implements Runnable {
@Override
public void run() {
int i=0;
while (i<10000){
System.out.println(i++);
}
}
}
实现类
Thread thread = new Thread(new CreateTread1());
thread.start();
特别实现 – Lambda表达式与双冒号
public class CreateThread2 {
public static void main(String[] args) {
//Lambda表达式写入run方法
Runnable runnable1 = ()->{
int i=0;
while (i<10000){
System.out.println(i++);
}
};
//双冒号::调用 CreateTread3 中的 MyMethod 方法 写入run方法
Runnable runnable = CreateTread3::MyMethod;
Thread thread3 = new Thread(runnable);
Thread thread2 = new Thread(runnable1);
thread3.start();
thread2.start();
}
}
class CreateTread3{
public static void MyMethod(){
System.out.println("运行");
}
}
- 实现Callable接口,重写call方法,创建FutureTask的实例并传入实现类的对象,再创建thread对象并传入FutureTask的对象,thread.start()开启,通过FutrueTask的对象的get方法得到call方法的返回值
public class CreateThread2 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask(new CreateTread3());
Thread thread = new Thread(futureTask);
thread.start();
System.out.println(futureTask.get());
}
}
class CreateTread3 implements Callable {
@Override
public Object call() throws Exception {
int i =0;
while (i<10000){
System.out.println("运行"+i++);
}
return i;//返回10000
}
}
测试写法
Callable callable = ()->{
System.out.println("运行");
return "运行完毕";
};
FutureTask futureTask2 = new FutureTask(callable);
Thread thread2 = new Thread(futureTask2);
thread2.start();
System.out.println(futureTask2.get());
停止线程
Thread thread3 = new Thread(){
@Override
public void run() {
int i =0;
if (!interrupted()){
System.out.println("停止运行了"+i);
}
}
};
thread3.start();
thread3.sleep(1000);
thread3.interrupt();