- Java语言的JVM允许程序运行多个线程,它通过java.lang.Thread类来实现。
- Thread类的特性
- 每个线程都是通过某个特定Thread对象的run()方法来完成操作的,通常把run()方法的主体称为线程体。
- 通过Thread对象的start()方法来调用这个线程。
- 继承Thread类
public class TestThread extends Thread {
@Override
public void run() {
System.out.println("多线程运行的主逻辑");
for (int i = 0; i < 100; i++) {
System.out.println("这是多线程的逻辑代码" + i);
}
}
}
- 编写一个测试类
public class Test {
public static void main(String[] args) {
Thread t = new TestThread();
t.start();
}
}
- 实现Runnable接口
public class TestRunnable implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"Runnable多线程运行代码");
for (int i = 0; i < 100; i++) {
System.out.println("Runnable多线程运行逻辑代码"+i);
}
}
}
- 编写一个测试类
public class Test {
public static void main(String[] args) {
Thread t2 = new Thread(new TestRunnable());
t2.start();
Thread t3 = new Thread(new TestRunnable(), "t-1");
t3.start();
}
}
- 一般使用实现Runnable接口的方式来实现多线程
- 避免了单继承的局限类
- 多线程可以共享一个接口实现类的对象,非常适合多个相同线程来处理同一份资源。
- wait():令当前线程挂起,并放弃CPU、同步资源,使别的线程可访问并修改共享资源,而当前线程排队等候再次对资源的访问。
- notify(): 唤醒正在排队等待同步资源的线程中优先级最高值结束等待。
- notifyAll():唤醒正在排队等待资源的所有线程。
- 这三个方法只能用在有同步锁的方法或者代码块中。



