每个运行程序可以看作是一个进程,进程中可以有多个执行单元同时进行,这些执行单元可以被看作成一条条的线索,被称为进程。
进程和线程一样,都是由cpu轮流执行的,只不过Cpu的运行速度很快,故而给人一种同时执行的感觉。
一,线程的创建
1,继承Thread类创建线程
(1)通过继承Thread类并重写run()的方法来创建线程
缺点:如果一个类继承了Thread就不能继承其它类
public class thread {
public static void main(String[] args) {
Mythread thread = new Mythread();
thread.start();
while (true){
System.out.println("线程1正在执行!!!");
}
}
class Mythread extends Thread{
public void run(){
while (true){
System.out.println("线程22222正在执行!!!!");
}
}
二,Runnable接口创建多线程
Thread类提供了另外一个构造方法Thread(Runnable target),Runnable是一个接口。它只有一个run()方法,
public static void main(String[] args) {
Mythread mythread = new Mythread();
Thread thread = new Thread(mythread);
thread.start();
while (true){
System.out.println("线程111111");
}
}
class Mythread implements Runnable{
@Override
public void run() {
while (true){
System.out.println("线程2222222");
}
}
}
Thread和Runnable的对比:
Thread不能共享资源,因为它传入的不是对象
Runnable可以共享资源,因为它将类的实例化对象传入了Thread类中,所以各个线程共享这个对象。