第一种:继承Thread
方法一:匿名内部类
//匿名内部类
public class ThreadDemo02 {
public static void main (String[] args) {
new Thread() {
@Override
public void run () {
for(int i = 0; i < 10; i++) {
System.out.println ("run" + i);
}
}
}.start ();
for(int i = 0; i < 10; i++) {
System.out.println ("main" + i);
}
}
}
方法二:自定义线程
//自定义线程
public class MyThread extends Thread{
/**
* run()方法就是线程要执行任务的方法
*/
@Override
public void run () {
// 一条新的执行路径
// 这个路径的触发方式不是调用run()方法,二十通过Thread对象中的start()方法来启动任务的
for (int i = 0; i < 10; i++){
System.out.println ("run" + i);
}
}
}
//测试
public class ThreadDemo01 {
public static void main (String[] args) {
MyThread myThread = new MyThread ();
myThread.start ();//启动进程任务
for (int i = 0; i < 10; i++) {
System.out.println ("main " + i);
}
}
}
因为java是抢占式调度所以运行的结果并不是唯一的
第二种:实现Runnable
/*
用于给线程进行执行的任务
*/
public class MyRunnable implements Runnable{
@Override
public void run () {
for(int i = 0; i < 10; i++) {
System.out.println ("runnable" + i);
}
}
}
public class RunnableDemo01 {
public static void main (String[] args) {
// 1、创建一个任务对象
MyRunnable myRunnable = new MyRunnable ();
// 2、创建一个线程,并为其分配一个任务
Thread thread = new Thread (myRunnable);
// 3、执行这个线程
thread.start ();
for (int i = 0; i < 10; i++) {
System.out.println ("main" + i);
}
}
}
实现Runnable 和 继承Thread性比如下优势
通过创建任务,然后给线程分配的方式来实现的多线程,更适合多个线程同时执行相同任务的情况
可以避免单继承所带来的局限性
任务与线程本身是分离的,提高了程序的健壮性
后续学习的线程池技术,接收Runnable类型的任务,不接收Thread类型的线程
第三种:Callable 接口(不常用)
public class CallableDemo01 {
public static void main (String[] args) {
Callable<Integer> c = new MyCallable();
FutureTask<Integer> task = new FutureTask<> (c);
new Thread(task).start ();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep (200);
} catch (InterruptedException e) {
e.printStackTrace ();
}
System.out.println (i);
}
}
//实现方法
static class MyCallable implements Callable<Integer> {
@Override
public Integer call () throws Exception {
for (int i = 0; i < 10; i++) {
Thread.sleep (200);
System.out.println (i);
}
return 100;
}
}
}
/*输出结果 交替执行
0
0
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
*/