一.程序,进程与线程的概念
程序是一组指令的有序集合,其本身没有任何的运行的含义,它只是一个静态的实体。
进程是程序在某个数据集上的执行,进程是一个动态的实体,有自己的生命周期。
线程是进程内一个相对独立的,可以调度的执行单元(又被称为轻量级进程)。线程必须拥有父进程。系统没有为线程分配资源,它与进程中的其他线程共享该进程的共享资源。同一进程的不同线程共享相同的地址空间,它们可以访问相同的变量和对象,实现线程间的信息共享。
二.多线程的概念
多线程程序指的是一个程序中包含多个执行流,它是实现并发机制的有效手段。多线程意味着一个程序的多个语句块同时执行,但是不等于多次启动一个程序。
三.引入多线程程序设计的原因
1.某些应用具有内在的多控制流结构,这些控制流具有合作性质,需要共享内容。
2.在需要多控制流的应用中,多线程比多进程在速度上具有绝对优势。
3.采用多线程可以提高处理机与设备之间的并行性。
4.在多处理机的环境下,多线程可以并行执行,从而提高资源利用率和进程推进速度。
下面举一个例子
class Storage
{
private String name;
private int max, num, no;
public Storage(String name, int max)
{
this.name = name;
this.max = max;
} //定义仓库类
public synchronized void input()
{
while (num >= max)
{
try{ wait();}catch (Exception e) {} }
num ++;
System.out.printf("生产%d号%s,当前库存数:%d\n",++no, name,num);
notify();
}
public synchronized void output()
{
while (num <= 0)
{
try{ wait();}catch (Exception e) {} }
num --;
System.out.printf("消费%d号%s,当前库存数:%d\n",no-num,name,num);
notify();
}
public String getName()
{
return this.name;
}
public int getMax()
{
return this.max;
}
} //定义仓库类的方法
class Producer extends Thread
{
Storage store;
public Producer(Storage store)
{
this.store = store;
} //定义生产者线程
public void run()
{
for(int i=0;i<10;i++)
{
store.input();
}
}
} //调用同步生产方法
class Consumer extends Thread
{
Storage store;
public Consumer(Storage store)
{
this.store = store;
} //定义消费者线程
public void run()
{
for(int i=0;i<10;i++)
{
store.output();
}
}
} //调用同步消费方法
public class Test2
{
public static void main(String[] args)
{
Storage store = new Storage("洗衣机",4);
System.out.println("构建最大库存为"+store.getMax()+store.getName()+"仓库\n");
Producer producer = new Producer(store);
Consumer consumer = new Consumer(store);
producer.start();
consumer.start();
}
} //定义主类
多线程机制是JAVA语言的重要特征之一。JAVA是基于操作系统级的多线程环境设计的,JVM依靠多线程来执行多任务。并且所有的类库在设计时都考虑到了多线程机制