public class MyTest01 {
public static void main(String[] args) {
Thread.currentThread().setName("主线程");
System.out.println(Thread.currentThread().getName()+":"+"我是主线程");
//创建一个新线程
ThreadDemo1 thread1 = new ThreadDemo1();
//为线程设置名称
thread1.setName("线程一");
//开启线程
thread1.start();
}
}
class ThreadDemo1 extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+":"+"我是线程一");
}
}
实现 Runnable 接口
public class MyTest02 {
public static void main(String[] args) {
Thread.currentThread().setName("主线程");
System.out.println(Thread.currentThread().getName()+":"+"我是主线程");
//创建一个新线程
Thread thread2 = new Thread(new ThreadDemo2());
//为线程设置名称
thread2.setName("线程二");
//开启线程
thread2.start();
}
}
class ThreadDemo2 implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":" + "我是线程二");
}
}
实现 Callable 接口
public class MyTest03 {
public static void main(String[] args) throws Exception{
Thread.currentThread().setName("主线程");
System.out.println(Thread.currentThread().getName()+":"+"我是主线程");
//创建FutureTask的对象
FutureTask<String> task = new FutureTask<String>(new ThreadDemo3());
//创建Thread类的对象
Thread thread3 = new Thread(task);
thread3.setName("线程三");
//开启线程
thread3.start();
//获取call()方法的返回值,即线程运行结束后的返回值
String result = task.get();
System.out.println(result);
}
}
class ThreadDemo3 implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println(Thread.currentThread().getName()+":"+"我是线程三");
return Thread.currentThread().getName()+":"+"结束返回值";
}
}
使用ThreadPool创建
public class MyTest04 {
public static void main(String[] args) throws InterruptedException {
Long start = System.currentTimeMillis();
final Random random = new Random();
final List<Integer> list = new ArrayList<>();
ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10000; i++){
executorService.execute(new Runnable() {
@Override
public void run() {
list.add(random.nextInt());
}
});
}
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.DAYS);
System.out.println("时间:" + (System.currentTimeMillis()-start));
System.out.println("大小" + list.size());
}
}