线程与进程,及线程的两种创建方式
定义:
1.进程:进程是一个应用程序运行时的内存分配空间,它负责分配整个应用程序的内存空间;
2.线程:其实就是进程中一个程序执行的控制单元,它负责的应用程序的执行顺序。
创建线程的两种方式和使用方法:
public class ThreadTestDriver {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
//第一种方法
ThreadTest threadTest = new ThreadTest("firstThread");
threadTest.start();
//第二种方法
Thread th = new Thread(new ThreadTest2("secondThread"));
th.start();
}
}
/**
* 创建线程的第一种方法:继承Thread,由子类复写run()方法
* @author Administrator
*
*/
class ThreadTest extends Thread{
public ThreadTest(String threadName){
super(threadName);
}
@Override
public void run() {
System.out.println("第一种创建线程的方式。");
System.out.println(Thread.currentThread().getName());
}
}
/**
* 创建线程第二种方式:实现一个接口Runnable,覆盖接口中的run()方法
* @author Administrator
*
*/
class ThreadTest2 implements Runnable{
private String threadName;
public ThreadTest2(String threadName){
this.threadName = threadName;
}
@Override
public void run() {
System.out.println("第二种创建线程的方式。");
Thread.currentThread().setName(threadName);
System.out.println(Thread.currentThread().getName());
}
}
通常创建线程都用第二种方式,因为实现Runnable接口可以避免单继承的局限性。
浙公网安备 33010602011771号