一、实现Runnable接口
- 步骤:
(1)创建自定义类并实现Runable接口
(2)实例化自定义的类
(3)将自定义的类的实例作为参数传给Thread类,创建thread实例
(4)调用thread实例的start()方法,启动子进程 - 代码:
class ThreadDemo implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"subThread starting ...");
int i = 0;
while (!Thread.currentThread().isInterrupted()){
System.out.println(i++);
}
System.out.println(Thread.currentThread().getName()+"subthread end... ");
}
}
public class Demo {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + "main Thread Starting");
RunnableThread runnableThread = new RunnableThread();
Thread thread = new Thread(runnableThread,"A");
thread.start();
System.out.println(Thread.currentThread().getName() + "main Thread end");
}
}
二、继承Thread类
- 步骤:
(1)创建自定义类并继承Thread类,并且重写run()方法
(2)实例化自定义的类
(3)通过实例化对象调用start方法来创建新线程 - 代码:
class ThreadDemo extends Thread {
private Thread thread;
public ThreadDemo(Thread thread) {
this.thread = thread;
}
public ThreadDemo(){
this.thread = null;
}
@Override
public void run() {
if(thread != null) {
try {
this.thread.join(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"running");
}
}
public class Demo {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + "main Thread Starting");
ThreadDemo threadDemo = new ThreadDemo();
threadDemo.start();
System.out.println(Thread.currentThread().getName() + "main Thread end");
}
}
三、实现Callable接口
- 步骤: (Callable接口的实现是线程池提供的一种创建线程的方式)
(1)实现Callable接口,并且重写call方法,该方法为线程执行体
(2)创建线程池(Executors工具类提供的方法创建线程池)
(3)创建Callable接口实现类的实例
(4)将实例对象通过线程池的submit方法提交给线程池从而创建新的线程 - 代码:
class CallableDemo implements Callable {
@Override
public Object call() throws Exception {
System.out.println("Call() start...");
return null;
}
}
public class Demo {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + "main Thread Starting......");
ExecutorService excutorService = Executors.newSingleThreadExecutor();
CallableDemo callableDemo = new CallableDemo();
Future<Integer> future =excutorService.submit(callableDemo);
try {
Integer integer = future.get();
future.cancel(true);
System.out.println(integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" main thread end...");
}
}