使用Thread类实现两个子线程: (3)线程1实现100以内的奇数和 线程2实现100以内的偶数和

时间: 2024-03-01 18:53:58 浏览: 26
下面是使用Thread类实现两个子线程的示例代码: ```java public class Main { public static void main(String[] args) throws InterruptedException { OddThread oddThread = new OddThread(); EvenThread evenThread = new EvenThread(); oddThread.start(); evenThread.start(); oddThread.join(); evenThread.join(); System.out.println("奇数和:" + oddThread.getSum()); System.out.println("偶数和:" + evenThread.getSum()); } } class OddThread extends Thread { private int sum = 0; @Override public void run() { for (int i = 1; i <= 100; i += 2) { sum += i; } } public int getSum() { return sum; } } class EvenThread extends Thread { private int sum = 0; @Override public void run() { for (int i = 2; i <= 100; i += 2) { sum += i; } } public int getSum() { return sum; } } ``` 在主线程中创建两个子线程OddThread和EvenThread,并启动它们。在两个子线程的run方法中分别计算100以内的奇数和偶数的和,并保存到变量sum中。在主线程中使用join方法等待两个子线程执行完毕,然后分别调用getSum方法获取它们的和。最后输出结果。

相关推荐

编写一个2线程程序:主线程每秒输出依次偶数0,2,4,8等偶数,另外一个线程每秒一次输出1、2、3、5等奇数,并且通过同步方法实现总的输出结果为 0、1、2、3、4按大小顺序一次输出。(提示:可以使用互斥锁实现同步)//参考例题2:thread2.c#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <string.h>#include #include <semaphore.h>void *thread_function(void *arg);pthread_mutex_t work_mutex; /* protects both work_area and time_to_exit */#define WORK_SIZE 1024char work_area[WORK_SIZE];int time_to_exit = 0;int main() { int res; pthread_t a_thread; void *thread_result; res = pthread_mutex_init(&work_mutex, NULL); if (res != 0) { perror("Mutex initialization failed"); exit(EXIT_FAILURE); } res = pthread_create(&a_thread, NULL, thread_function, NULL); if (res != 0) { perror("Thread creation failed"); exit(EXIT_FAILURE); } pthread_mutex_lock(&work_mutex); printf("Input some text. Enter 'end' to finish\n"); while(!time_to_exit) { fgets(work_area, WORK_SIZE, stdin); pthread_mutex_unlock(&work_mutex); while(1) { pthread_mutex_lock(&work_mutex); if (work_area[0] != '\0') { pthread_mutex_unlock(&work_mutex); sleep(1); } else { break; } } } pthread_mutex_unlock(&work_mutex); printf("\nWaiting for thread to finish...\n"); res = pthread_join(a_thread, &thread_result); if (res != 0) { perror("Thread join failed"); exit(EXIT_FAILURE); } printf("Thread joined\n"); pthread_mutex_destroy(&work_mutex); exit(EXIT_SUCCESS);}void *thread_function(void *arg) { sleep(1); pthread_mutex_lock(&work_mutex); while(strncmp("end", work_area, 3) != 0) { printf("You input %d characters\n", strlen(work_area) -1); work_area[0] = '\0'; pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); while (work_area[0] == '\0' ) { pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); } } time_to_exit = 1; work_area[0] = '\0'; pthread_mutex_unlock(&work_mutex); pthread_exit(0);}

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include #include <semaphore.h> void * pthread_odd_function(void * arg); void * pthread_even_function(void * arg); pthread_mutex_t work_mutex; pthread_cond_t work_cond; #define MAX_COUNT 10 int count = 0; int main(int argc, char const *argv[]) { pthread_t pthread_odd; pthread_t pthread_even; pthread_attr_t pthread_attr; int res; res = pthread_attr_init(&pthread_attr);//init pthread attribute,step 1 if (res != 0){ perror("pthread_attr_init failed!"); exit(EXIT_FAILURE); } res = pthread_cond_init(&work_cond,NULL); if (res != 0){ perror("pthread_cond_init failed!"); exit(EXIT_FAILURE); } res = pthread_mutex_init(&work_mutex,NULL); if (res != 0){ perror("pthread_mutex_init failed!"); exit(EXIT_FAILURE); } pthread_attr_setdetachstate(&pthread_attr,PTHREAD_CREATE_DETACHED);//design pthread attribute step 2 res = pthread_create(&pthread_odd,&pthread_attr,pthread_odd_function,NULL);//step 3 if (res != 0){ perror("pthread_create failed!"); exit(EXIT_FAILURE); } res = pthread_create(&pthread_even,&pthread_attr,pthread_even_function,NULL); if (res != 0){ perror("pthread_create failed!"); exit(EXIT_FAILURE); } while(count < MAX_COUNT) ; //wait the two sons threads finished pthread_mutex_destroy(&work_mutex); pthread_cond_destroy(&work_cond); pthread_exit(NULL); return 0; } void * pthread_odd_function(void *arg)//step 4 { pthread_mutex_lock(&work_mutex); while(count < MAX_COUNT){ if (count % 2 == 1){ printf("the odd count is : %d\n", count); ++count; pthread_cond_signal(&work_cond);//in order to release the thread of even } else pthread_cond_wait(&work_cond,&work_mutex);//the pthread is blocked,wait for the condition } pthread_mutex_unlock(&work_mutex); } void * pthread_even_function(void *arg)//step 5 { pthread_mutex_lock(&work_mutex); while(count < MAX_COUNT){ if (count % 2 == 0){ printf("the even count is : %d\n", count); ++count; pthread_cond_signal(&work_cond);//in order to release the thread of odd } else pthread_cond_wait(&work_cond,&work_mutex);//wait the condition satisfied } pthread_mutex_unlock(&work_mutex); }给我讲一下这段代码

最新推荐

recommend-type

Java多线程--等待所有子线程执行完的五种方法.docx

Java多线程--等待所有子线程执行完的五种方法 Java多线程--等待所有子线程执行完的五种方法 Java多线程--等待所有子线程执行完的五种方法 Java多线程--等待所有子线程执行完的五种方法 Java多线程--等待所有子线程...
recommend-type

Java多线程--让主线程等待所有子线程执行完毕在执行

Java主线程等待所有子线程执行完毕在执行,其实在我们的工作中经常的用到,本篇文章就介绍了Java多线程--让主线程等待所有子线程执行完毕在执行,有需要的可以了解一下。
recommend-type

C#子线程更新UI控件的方法实例总结

主要介绍了C#子线程更新UI控件的方法,在桌面应用程序中控制UI界面有着不错的实用价值,需要的朋友可以参考下
recommend-type

python进阶之多线程对同一个全局变量的处理方法

今天小编就为大家分享一篇python进阶之多线程对同一个全局变量的处理方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

C#子线程执行完后通知主线程的方法

下面小编就为大家带来一篇C#子线程执行完后通知主线程的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

解答下列问题:S—>S;T|T;T—>a 构造任意项目集规范族,构造LR(0)分析表,并分析a;a

对于这个文法,我们可以构造以下项目集规范族: I0: S -> .S S -> .T T -> .a I1: S -> S. [$ T -> T. [$ I2: S -> T. I3: S -> S.;S S -> S.;T T -> T.;a 其中,点(.)表示已经被扫描过的符号,;$表示输入串的结束符号。 根据项目集规范族,我们可以构造出LR(0)分析表: 状态 | a | $ ---- | - | - I0 | s3| I1 | |acc I2 | | 其中s3表示移进到状态3,acc表示接受。在分析字符串a;a时,我们可以按照以下步骤进行
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。