一:线程的创建
- 继承Thread类 重写run方法
public class MyTest {
public static void main(String[] args) {
MyJob mj = new MyJob();
mj.start();
}
}
class MyJob extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("MyJob:" + i);
}
}
}
- 实现Runnable接口 重写run方法(用的最多的)
public class MiTest {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread t1 = new Thread(myRunnable);
t1.start();
}
}
class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("MyRunnable:" + i);
}
}
}
最常用的方式是
匿名内部类方式:
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("thread:" + i);
}
}
}).start();;
lambda方式:
Thread t2 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println("thread:" + i);
}
}).start();
-
实现Callable接口 重写call方法,配合FutureTask
特点:可以返回结果
public class MiTest {public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable myCallable = new MyCallable();
FutureTask futureTask = new FutureTask(myCallable);
//创建Thread线程
Thread t1 = new Thread(futureTask);
//启动线程
t1.start();
//获取结果
Object count = futureTask.get();
System.out.println("返回结果:" + count);
}
}
class MyCallable implements Callable{
@Override
public Object call() throws Exception {
int count = 0;
for (int i = 0; i < 10; i++) {
count += i;
}
return count;
}
}
4. 基于线程池构建线程
二:Java中线程的6种状态
![](/i/l/?n=24&i=blog/3517912/202409/3517912-20240919210531382-887250255.png)
说明:
NEW(新建状态):Thread对象被创建出来了,但是还没有执行start方法。
RUNNABLE(就绪状态):Thread对象调用了start方法,就为RUNNABLE状态(CPU调度/没有调度)
BLOCKED(阻塞状态):synchronized没有拿到同步锁,被阻塞的情况
WAITING(等待状态):调用wait方法就会处于WAITING状态,需要被手动唤醒
TIME_WAITING(超时等待):调用sleep方法或者join方法,会被自动唤醒,无需手动唤醒
TERMINATED(结束状态):run方法执行完毕,线程生命周期到头了
BLOCKED、WAITING、TIME\_WAITING:都可以理解为是阻塞、等待状态,因为处在这三种状态下,CPU不会调度当前线程
标签:Java,Thread,void,start,线程,内容,new,public
From: https://www.cnblogs.com/chengdanally/p/18420608