1、继承thread类
public class Mythread extends Thread{
@Override
public void run(){
// 这里写入 task code;
System.out.println(Thread.currentThread().getName());
}
/**
* 创建线程的第一种方法,继承thread,然后重写它的run方法
* @param args
*/
public static void main(String[] args) {
Mythread mythread = new Mythread();
mythread.setName("线程demo");
mythread.start();
}
}
2、实现runable接口
public class MyRunable implements Runnable{
@Override
public void run() {
// 这里写入task code
System.out.println(Thread.currentThread().getName());
}
/**
* 创建线程的方法表
* 实现runable接口,并重写它的run方法;
* @param args
*/
public static void main(String[] args) {
Thread thread = new Thread(new MyRunable());
thread.setName("xianchegn");
thread.start();
}
}
3、使用lambda表达式
/**
* 使用lambda表达式来实现线程
*/
public class LambdaDemo {
public static void main(String[] args) {
new Thread(
()->{
System.out.println(Thread.currentThread().getName());
}
).start();
}
}
4、利用线程池
/**
* 利用线程池
*/
public class Threadpool {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute( ()->{
System.out.println(Thread.currentThread().getName());
});
}
}
5、使用匿名内部类
public class Mythread implements Runnable{
/**
* 创建线程的方法3
* 使用匿名内部类的方式
* @param args
*/
public static void main(String[] args) {
// 创建线程
Thread thread = new Thread( new Runnable() {
@Override
public void run() {
// 线程的代码 task code
System.out.println(Thread.currentThread().getName());
}});
thread.setName("\"方法3 的线程,采用匿名内部类的方式\"");
thread.start();
}