当前位置:   article > 正文

10 Concurrent and Distributed Programming(并行与分布式程序设计 )课程总结_分布式与并行式计算课程总结与反思

分布式与并行式计算课程总结与反思

                                                                     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()启动线程,启动线程的两种方法

 

  1. public class HelloThread extends Thread {
  2. public void run(){
  3. System.out.println("Hello from a thread");
  4. }
    //方法1
  public static void main(String args[]){
  1. HelloThread p = new HelloThread();
  2. p.start();
  3. }
  //方法2    
  public static void main (String ars[]){
  1. (new HelloThread()).start();
  2. }
  3. }
       ways to create a thread:provide a Runnable object

             Runnable接口定义了一个名为run()的方法,该方法旨在包含在线程中执行的代码。Runnable对象被传递给线程构造函数。

 

  1. public class HelloThread implements Runnable {
  2. public void run(){
  3. System.out.println("Hello from a thread");
  4. }
  5. public static void main (String ars[]){
  6. (new Thread(new HelloThread())).start();
  7. }

}

一个非常常见的习惯用法是使用一个匿名可运行的线程启动

 

  1. public class HelloThread implements Runnable {
  2. public void run(){
  3. System.out.println("Hello from a thread");
  4. }
  5. public static void main (String ars[]){
  6. new Thread(new Runnable(){
  7. public void run(){
  8. System.out.println("1");
  9. }
  10. }).start();
  11. }
  12. }
未完待续
 

 

 

 

            

 

 

 

 

 

 

 

 

 

 

 

 

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
  

闽ICP备14008679号