您的位置:首页 > 编程语言

代码与程序的区别与联系

2017-08-08 11:02 232 查看
代码与程序的区别与联系,你真的懂么?请试着解释下面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的区别
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: