进程与线程
进程:一个进程就是一个执行中的程序,而每一个进程都有自己独立的一块
内存空间、一组系统资源,每一个进程的内部数据和状态都是完全独立的。
线程:Java程序执行中的单个顺序的流控制称为线程,多线程则指一个进程中可
以同时运行多个不同的线程,执行不同的任务。
区别:同类的多个线程共享一块内存空间和一组系统资源,而线程本身的数据通常只有微处理器的寄存器数据,以及一个供程序执行时使用的堆栈。所以系统在产生一个线程,或者在各个线程之间切换时,负担要比进程小的多 。
进程的创建
1.直接继承线程Thread类。该方法编写简单,可以直接操作线程,由于已经继承了Thread,不能再继承其他类了;
创建及启动线程:
public MyThread extends Thread{
// override run() of Thread —覆盖Thread类的run方法
public void run() {
线程体逻辑 }
}
MyThread t = new MyThread();
t.start();
👇
public class mythread extends Thread{
public static void main(String arg[]) {
mythread m=new mythread();
m.start();
System.out.println("This is the main thread");
}
public void run() {
System.out.println("This is another thread");
}
}
//This is the main thread
//This is another thread
2.实现Runnable接口。当一个类已继承了另一个类时,就只能用实现Runnable接口的方式来创建线程;另外,使用此方法的更多原因是多个线程共享某个对象的资源。
创建及启动线程:
public MyThread implements Runnable {
// implement run() of Runnable
public void run() {
线程体逻辑 }
}
MyThread t = new MyThread();
Thread t1 = new Thread(t);
t1.start();
👇
public class mythread2{
public static void main(String[] arg) {
my t=new my();
Thread tt=