接下来介绍Java多线程,首先介绍下进程和线程
进程:简而言之理解为任务管理器中运行的独立程序
线程:是在进程中独立运行的子任务
一个进程运行时,至少会有一个线程在运行的
使用多线程的优点
最大限度的利用CPU的空闲时间来处理其他的任务
接下来看一个简单的java多线程案例
import org.junit.Test;
class MyThread extends Thread {
@Override
public void run() {
super.run();
System.out.println("我的线程");
}
}
public class ThreadStudy {
@Test
public void getName() {
System.out.println(Thread.currentThread().getName());
MyThread thread = new MyThread();
thread.start();
}
}
CPU执行线程是有不确定性的,可以看下面代码的输出结果是具有不确定性的,并且执行start()方法的顺序并不代表启动的顺序
public class RandomThread extends Thread{
@Override
public void run() {
try {
for(int i=0; i<10; i++) {
int time = (int) (Math.random() * 1000);
Thread.sleep(time);
System.out.println("run=" + Thread.currentThread().getName());
}
}catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
RandomThread thread = new RandomThread();
thread.setName("thread");
thread.start();
for(int i=0; i<10; i++) {
int time = (int) (Math.random() * 1000);
Thread.sleep(time);
System.out.println("main=" + Thread.currentThread().getName());
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
但是如果我们想要创建的类A此时已经有一个父类B,而父类B因为某种不可知的原因不能继承Thread类,那么A就不能继承Thread类,因为Java是不支持多继承的,所以此时我们可以使用Runnable接口
public class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("MyRunnable");
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
System.out.println("运行结束!");
}
}