1.使用Thread创建线程
1.1使用匿名内部类
public class TestThread {
public static void main(String[] args) {
Thread thread = new Thread(){
@Override
public void run() {
System.out.println("new thread running"+"->"+ LocalDateTime.now().toString());
}
};
thread.setName("t1");//可以为线程设置名字
thread.start();
System.out.println("main running"+"->"+LocalDateTime.now().toString());
/*运行结果 这两个进程属于两个不同的指令序列,这个结果说明,这两个指令序列在底层是由cpu并行执行的
//至于是不是并行执行是由底层控制的,我们干涉不了
main running->2020-03-16T16:28:16.805
new thread running->2020-03-16T16:28:16.805*/
}
}
1.2不适用匿名内部类
public class TestThread {
public static void main(String[] args) {
test t = new test();
Thread thread = new Thread(t);
thread.start();
}
}
class test extends Thread{
@Override
public void run() {
System.out.println("running");
}
}
2.使用Runnbale
2.1使用匿名内部类
public class TestRunnable {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("new thread running"+"->"+LocalDateTime.now().toString());
}
};
Thread thread= new Thread(runnable);
thread.start();
}
}
2.2不使用匿名内部类
public class TestRunnbale2 {
public static void main(String[] args) {
test2 t= new test2();
Thread thread= new Thread(t);
thread.start();
}
}
class test2 implements Runnable{
@Override
public void run() {
System.out.println("new thread running"+"->"+ LocalDateTime.now().toString());
}
}
3.有返回值的创建线程(//FutureTask 能够接收 Callable 类型的参数,用来处理有返回结果的情况)
package smy.BaseThread;
import java.time.LocalDateTime;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class TestFutureTask {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//泛型是返回值的类型;
//传入callable参数,内部的call()方法是线程任务;
//线程启动时调用call(),和以往两种方法不同的是这个call()方法带有返回值,而以往的run()方法不带有返回值
//之前是在Runnable类里实现run(),这里是在传入的callable参数里实现call();
FutureTask<Integer> task = new FutureTask<>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("running"+"->"+LocalDateTime.now().toString());
Thread.sleep(2000);//主线程等待sleep的时间得到下面返回值
return 100;
}
});
//参数一是任务对象,参数二是线程名字,推荐
Thread thread=new Thread(task,"t1");
thread.start();
int callback = task.get();
//获取返回值(由于上面设置了两秒的睡眠时间,所以在时间结束之前主线程阻塞在这里)
System.out.println("返回值:"+callback+"->"+LocalDateTime.now().toString());
/*运行结果
* running->2020-03-16T18:05:59.768
返回值:100->2020-03-16T18:06:01.770
* 由上可知:在这里,主线程和新创建的线程是并行执行的,运行结果差两秒
* */
}
}