赞
踩
10.1 并行与线程安全
1、什么是并发程序
multiple computations happen at the same time.
举例:网络上的多台计算机、一台计算机上的多个应用或多个处理器等
Two Models for Concurrent Programming:
(1)共享内存:在内存中读写共享数据
(2)消息传递:通过channel传递消息
2、 Processes, Threads, Time-slicing
并发模块分为两种类型:进程(processes)和线程(threads)
对于进程,每个进程在计算机上有着自己独自的内存空间,不同的进程(processes)之间是相互隔离的。一个进程是某个与其他程序隔离的正在运行的程序的一个实例
对于线程,进程是具有一定独立功能的程序关于某个数据集合上的一次运行活动,程序内部的控制机制
(1)Processes
进程拥有整台计算机的资源,多进程之间不共享内存,进程之间通过消息传递进行协作
OS支持的PC机制(pipe/socket)支持进程间通信。JVM通常运行单一进程,但也可以创建新的进程
一般来说,进程==程序==应用
(2)Threads
进程==虚拟机,线程==虚拟cpu。程序共享、资源共享,都隶属于进程。共享内存。很难获得线程私有的内存空间
通过创建消息队列在线程之间进行消息传递
每个应用至少有一个线程,主线程可以创建其他线程。
创建新线程有两种方式,一是从Thread类中派生子类,二是从Runnable接口中构造Thread对象
ways to creat a thread:继承Thread类,调用Thread.start()启动线程,启动线程的两种方法
- public class HelloThread extends Thread {
- public void run(){
- System.out.println("Hello from a thread");
- }
//方法1
public static void main(String args[]){
- HelloThread p = new HelloThread();
- p.start();
- }
//方法2
public static void main (String ars[]){
- (new HelloThread()).start();
- }
- }
ways to create a thread:provide a Runnable object
Runnable接口定义了一个名为run()的方法,该方法旨在包含在线程中执行的代码。Runnable对象被传递给线程构造函数。
- public class HelloThread implements Runnable {
- public void run(){
- System.out.println("Hello from a thread");
- }
- public static void main (String ars[]){
- (new Thread(new HelloThread())).start();
- }
}
一个非常常见的习惯用法是使用一个匿名可运行的线程启动
- public class HelloThread implements Runnable {
- public void run(){
- System.out.println("Hello from a thread");
- }
- public static void main (String ars[]){
- new Thread(new Runnable(){
- public void run(){
- System.out.println("1");
- }
- }).start();
- }
- }
未完待续
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。