创建一个线程:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());//打印当前线程名字
int i = 0;
while (i<5){
System.out.println(i);
i++;
}
}
});
thread.setName("test_new_thread"); //为创建的线程设置名字
thread.start();
在jdk的1.8版本以后,使用lambda可以这么写
Thread thread = new Thread(() -> {
System.out.println(Thread.currentThread().getName());//打印当前线程名字
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
});
thread.setName("lambda_new_thread");
thread.start();
//直接启动线程
new Thread(()->{
System.out.println(Thread.currentThread().getName());//打印当前线程名字
int i = 0;
while (i<5){
System.out.println(i);
i++;
}
}).start();
注意,如果一个线程多次调用start()方法,会出现非法线程状态异常:
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)
at com.test.thread.MyThread.main(MyThread.java:21)
所以一个线程只能调用一次start()方法。