体验多线程抢占 CPU 资源的测试
public class test0 {
public static void main(String[] args) {
System.out.println("hello world");
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
System.out.println("hello world");
}
}
class MyRunnable implements Runnable{
@Override
public void run(){
System.out.println("hello myRunnable" + Thread.currentThread().getName());
}
}
start() 和 run() 之间的区别
start() 函数用来启动线程,真正实现了多线程运行。
run() 函数只是类的一个普通函数,如果直接调用 run 方法,程序中依然只有主线程这一个线程。
IllegalComponentStateException 异常
IllegalComponentStateException 异常是 RuntimeException 异常的父类,指无效状态异常,在不合理或不正确时间内唤醒一方法时出现的异常信息。
报异常,单个对象的 start() 方法不能多次重复调用
public class test1{
public static void main(String[] args){
Thread MyThread = new MyThread();
for(int i = 0; i < 2; i++){
MyThread.start();
}
}
}
class MyThread extends Thread{
@Override
public void run(){
System.out.println("hello myThread" + Thread.currentThread().getName());
}
}
不报
public class test2{
public static void main(String[] args){
for(int i = 0; i < 2; i++){
Thread MyThread = new MyThread();
MyThread.start();
}
}
}
class MyThread extends Thread{
@Override
public void run(){
System.out.println("hello myThread" + Thread.currentThread().getName());
}
}
不报
public class test3{
public static void main(String[] args){
Thread MyThread = new MyThread();
for(int i = 0; i < 2; i++){
MyThread.run();
}
}
}
class MyThread extends Thread{
@Override
public void run(){
System.out.println("hello myThread" + Thread.currentThread().getName());
}
}
扩展
- 线程大体的五种状态:新建、就绪、运行、阻塞、结束,其中就绪分为无限期等待和限期等待
- 对就绪做出最简单的比方,sleep()休息一会再自动启动,不设timeout参数的wait()需要其他线程唤醒
- 先看一下下面这个图,对线程的状态之间的关系有个大概的了解
- 有时候代码的执行顺序并不是你表面上看到的那样,Java虚拟机会对代码进行优化重排,提升机器的运行效率
- Java语言中还有个先行发生原则