当一个程序开始运行时,它就是一个进程,进程包含运行中的程序和程序所使用的内存和系统资源。而一个进程又是由多个线程组成的。引入线程优点是易于调度,提供开发效率,通过线程可以方便有效的实现并发,进程可创建多个线程来执行同一个程序的不同部分,开销小,创建线程比创建进程要快,所需开销很少。
class TestThread extends Thread{
private String name;
public TestThread(String name) {
super();
this.name = name;
}
public void run() {
for(int i = 0;i < 10;i++) {
System.out.println("线程信息:"+this.name+",i="+i);
}
}
}public class ThreadDemo {
public static void main(String[] args) {
TestThread tt1 = new TestThread("这里是张三");
TestThread tt2 = new TestThread("这里是李四");
tt.start();
tt.start();
}
}代码如下:
public class TestThread implements Runnable{
private String name;
public TestThread(String name) {
super();
this.name = name;
}
public void run() {
for(int i = 0;i < 10;i++) {
System.out.println("线程信息:" + this.name + ",i = " +i);
}
}
} 然而在Runnable的子类中没有start() 方法,只有Thread类中才有 。此时视察Thread类,有一个构造函数:public Thread(Runnable targer) 此构造函数接受Runnable的子类实例,也就是说可以通过Thread类来启动Runnable实现多线程 。(start() 可以协调系统的资源):
public class ThreadDemo {
public static void main(String[] args) {
TestThread tt1 = new TestThread("这里是张三");
TestThread tt2 = new TestThread("这里是李四");
new Thread(tt1).start();
new Thread(tt2).start();
}
}
以卖票程序为例,通过Thread类实现:
class TicketThread extends Thread {
private int ticket = 1000;
public void run(){
for(int i = 0;i < 1000;i++) {
if(this.ticket > 0){
System.out.println("卖票:ticket"+this.ticket--);
}
}
}
}public class ThreadTicket {
/**
* 继承Thread
*/
public static void startThread(){
TicketThread tt1 = new TicketThread();
TicketThread tt2 = new TicketThread();
TicketThread tt3 = new TicketThread();
tt1.start();//每个线程都各卖了1000张,共卖了3000张票
tt2.start();
tt3.start();
}
/**
* 实现Runable接口
*/
public static void startRunable(){
TicketThread tt = new TicketThread();
new Thread(tt).start();//同一个mt
new Thread(tt).start();
new Thread(tt).start();
}
public static void main(String[] args) {
startThread();
startRunable();
}
}
原文地址:http://blog.csdn.net/ljtyzhr/article/details/41521277