定义:
1.进程:进程是一个应用程序运行时的内存分配空间,它负责分配整个应用程序的内存空间;
2.线程:其实就是进程中一个程序执行的控制单元,它负责的应用程序的执行顺序。
创建线程的两种方式和使用方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 |
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接口可以避免单继承的局限性。
线程与进程,及线程的两种创建方式,布布扣,bubuko.com
原文:http://www.cnblogs.com/lxricecream/p/3592599.html