本文共 3364 字,大约阅读时间需要 11 分钟。
/* test1.c */#include#include #include #include #include void *thread_1(void *);void main(){ char msg[] = "1"; printf("main-thread running. msg:%s\n", (char *)msg); void *r_msg; pthread_t pth1; // 忽略错误检查 int res = pthread_create(&pth1, NULL, thread_1, msg); // 创建并启动线程 pth1 printf("waiting for pth1-thread.\n"); // 忽略错误检查 res = pthread_join(pth1, &r_msg); // main 线程等待 pth1 线程执行完毕 printf("main-thread done. r_msg:%s, msg:%s\n", (char *)r_msg, (char *)msg);}void *thread_1(void *arg){ printf("pth1-thread running. arg:%s\n", (char *)arg); sleep(2); strcpy((char *)arg, "2"); printf("pth1-thread done.\n"); pthread_exit("ccc");}
运行结果如下:
ubuntu@cuname:~/dev/beginning-linux-programming/test$ gcc -o test1 test1.c -lpthreadubuntu@cuname:~/dev/beginning-linux-programming/test$ ./test1main-thread running. msg:1waiting for pth1-thread.pth1-thread running. arg:1pth1-thread done.main-thread done. r_msg:ccc, msg:2
public class CreateThread { public static void main(String[] args) throws InterruptedException { // 这里使用 StringBuilder 而没有使用 String ,是因为 String 类型的对象本身不可修改, // 给 String 类型的变量赋值,其实是将新的 String 对象赋值给该变量, // 而传递到线程 run 方法中的变量被要求为 final 或 事实上为 final, // 意思是 要么该变量由 final 修饰,要么该变量仅仅被赋值一次, // 也就是变量的值不可变。但是可以修改该变量指向的对象的内容。 StringBuilder msg = new StringBuilder("1"); StringBuilder r_msg = new StringBuilder(); System.out.println("main-thread running. msg:" + msg); Thread pth1 = new Thread(new Runnable() { // 创建一个线程对象 @Override public void run() { System.out.println("pth1-thread running. arg:" + msg); try { Thread.sleep(1 * 1000); // 线程 pth1 睡眠 1 秒 } catch (InterruptedException e) { // ignore } msg.delete(0, msg.length()).append("2"); r_msg.delete(0, r_msg.length()).append("ccc"); System.out.println("pth1-thread done."); } }); pth1.start(); // 启动线程 pth1 System.out.println("waiting for pth1-thread."); pth1.join(); // main 线程等待 pth1 线程执行完毕 System.out.println("main-thread done. r_msg:" + r_msg + ", msg:" + msg); }}
运行结果如下:
main-thread running. msg:1waiting for pth1-thread.pth1-thread running. arg:1pth1-thread done.main-thread done. r_msg:ccc, msg:2
#include// 取消一个线程(向指定线程 thread 发送取消请求)int pthread_cancel(pthread_t thread);// 线程设置自身的取消状态取值为:// PTHREAD_CANCEL_ENABLE 接收取消请求// PTHREAD_CANCEL_DISABLE 忽略取消请求int pthread_setcancelstate(int state, int *oldstate);// 设置取消类型// PTHREAD_CANCEL_ASYNCHRONOUS 接收到取消请求后立即退出// PTHREAD_CANCEL_DEFERRED 接收到取消请求后,直到遇到 ***取消点*** 时才执行退出// 可以作为 取消点 的函数有:pthread_testcancel / pthread_join / pthread_cond_wait /// pthread_cond_timedwait / sem_wait / sig_wait 等// 根据 POSIX 标准,其他可能阻塞的系统调用,如 read / wait / sleep 等也可以成为取消点。int pthread_setcanceltype(int type, int *oldtype);
转载地址:http://xclsi.baihongyu.com/