代码与程序的区别与联系

来源:互联网 发布:日本听歌软件 编辑:程序博客网 时间:2024/06/07 15:09

代码与程序的区别与联系,你真的懂么?请试着解释下面2段代码。

//第一段程序:fork与多进程#include <unistd.h>#include <stdio.h> int main () {     pid_t fpid=fork();     if (fpid < 0) printf("error in fork!");     else if (fpid == 0) printf("i am the child process, my process id is %d/n",getpid());     else printf("i am the parent process, my process id is %d/n",getpid());     return 0;}
//第二段程序:sleep(wait)与多线程public class ThreadTest implements Runnable {    int number = 10;    public void firstMethod() throws Exception {        synchronized (this) {            number += 100;            System.out.println(number);        }    }    public void secondMethod() throws Exception {        synchronized (this) {            Thread.sleep(2000);//1.sleep的是哪个线程? 2.如果把本行换成下一行的语句,程序执行会有什么不同?            //this.wait(2000);            number *= 200;        }    }    @Override    public void run() {        try {            firstMethod();        } catch (Exception e) {            e.printStackTrace();        }    }    public static void main(String[] args) throws Exception {        ThreadTest threadTest = new ThreadTest();        Thread thread = new Thread(threadTest);        thread.start();        threadTest.secondMethod();    }}

能看得懂这2段代码,才算是入门了吧~ (有的时候口头上能说出来和真正的理解可不一样 ←_←)

总结:代码只有一份,新建一个进程或线程不过是新建了一个“上下文”或“程序指针”(程序计数器PC),重新指向原来那段代码。

附:

[1] linux中fork()函数详解(原创!!实例讲解)
[2] Java Thread(线程)案例详解sleep和wait的区别