多线程
进程,是对运行时程序的封装,是系统进行资源调度和分配的基本单位,实现了操作系统的并发。
线程,是进程的一个实体,是 CPU 调度和分派的基本单位,是比进程更小的能独立运行的基本单位。
创建线程的三种方式
继承 Thread 类
实现 Runnable 接口
实现 Callable 接口
public class ThreadDemo extends Thread {
@Override
public void run() {
System.out.println("继承Thread类");
}
public static void main(String[] args) {
ThreadDemo threadDemo = new ThreadDemo();
threadDemo.start();
}
}
public class RunnableDemo implements Runnable {
@Override
public void run() {
System.out.println("实现Runnable接口");
}
public static void main(String[] args) {
Thread thread = new Thread(new RunnableDemo());
thread.start();
}
}
public class CallableDemo implements Callable<String> {
@Override
public String call() throws Exception {
return "实现Callable接口";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> futureTask = new FutureTask<>(new CallableDemo());
new Thread(futureTask).start();
System.out.println(futureTask.get());
}
}
run()方法是线程的执行体,线程对象的 start()方法用于启动线程,使线程进入就绪状态,当线程获得 CPU 时间片后,就会执行 run()方法。
控制线程的方法
sleep():让当前线程休眠指定时间,不释放锁。
yield():让当前线程让出 CPU,重新进入就绪状态。
join():等待线程终止。
interrupt():中断线程。
wait():让线程等待,释放锁。
notify():唤醒等待线程。
notifyAll():唤醒所有等待线程。
sleep()方法的作用是让当前线程休眠指定时间,不释放锁,线程休眠时间到后,线程进入就绪状态,等待 CPU 调度。
public class ThreadControlDemo {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
yield()方法的作用是让当前线程让出 CPU,重新进入就绪状态,等待 CPU 调度。
public class ThreadControlDemo {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
Thread.yield();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
});
thread1.start();
thread2.start();
}
}
join()方法的作用是等待线程终止,当前线程等待调用 join()方法的线程终止后,再继续执行。
public class ThreadControlDemo {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
});
thread1.start();
try {
// 等待线程1终止,才轮到线程2
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
thread2.start();
}
}
获取线程的执行结果
线程的5中状态
最后更新于
这有帮助吗?