线程-输出1到100之间的偶数,创建2个线程,使用join方法让主线程main阻塞,让子线程执行,观察结果

package 线程;

public class JoinDome extends Thread {
     
@Override
public void run() {
int sum=0;
for(int i=0;i<=100;i++){
if(i%2==0){
sum=i+sum;
}
}
System.out.println(Thread.currentThread().getName()+"\t"+sum);
 
      }
}
public class JoinTest {


public static void main(String[] args)  {
int i;
for(i=0;i<7;i++){
if(i==3){
JoinDome jd=new JoinDome();
jd.setName("线程1");
   jd.start();
   try {
jd.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}System.out.println(Thread.currentThread().getName()+"\t"+i);
}
}


}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是使用 C 语言实现的代码: ```c #include <stdio.h> #include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t even_cond = PTHREAD_COND_INITIALIZER; pthread_cond_t odd_cond = PTHREAD_COND_INITIALIZER; int count_even = 0; int count_odd = 0; void* input_thread(void* arg) { while (1) { int num; scanf("%d", &num); pthread_mutex_lock(&mutex); if (num % 2 == 0) { ++count_even; if (count_even == 3) { count_even = 0; pthread_cond_broadcast(&even_cond); } } else { ++count_odd; if (count_odd == 3) { count_odd = 0; pthread_cond_broadcast(&odd_cond); } } pthread_mutex_unlock(&mutex); } return NULL; } void* output_even_thread(void* arg) { while (1) { pthread_mutex_lock(&mutex); while (count_even != 3) { pthread_cond_wait(&even_cond, &mutex); } for (int i = 0; i < 3; ++i) { printf("%d ", i * 2); } printf("\n"); pthread_mutex_unlock(&mutex); } return NULL; } void* output_odd_thread(void* arg) { while (1) { pthread_mutex_lock(&mutex); while (count_odd != 3) { pthread_cond_wait(&odd_cond, &mutex); } for (int i = 0; i < 3; ++i) { printf("%d ", i * 2 + 1); } printf("\n"); pthread_mutex_unlock(&mutex); } return NULL; } int main() { pthread_t tid_input, tid_output_even, tid_output_odd; pthread_create(&tid_input, NULL, input_thread, NULL); pthread_create(&tid_output_even, NULL, output_even_thread, NULL); pthread_create(&tid_output_odd, NULL, output_odd_thread, NULL); pthread_join(tid_input, NULL); pthread_join(tid_output_even, NULL); pthread_join(tid_output_odd, NULL); return 0; } ``` 这里使用了 POSIX 线程库来实现线程间的同步。三个线程分别是输入线程输出偶数线程输出奇数线程。 输入线程获取一个数字后,如果是偶数,就将 `count_even` 加 1,如果已经有 3 个偶数了,就唤醒等待偶数输出线程;如果是奇数,则将 `count_odd` 加 1,如果已经有 3 个奇数了,就唤醒等待奇数的输出线程。注意要在修改变量之前加锁,避免并发修改导致数据不一致。 输出线程会等待条件变量,如果没有满足条件就阻塞等待,直到条件满足后才开始输出输出完毕后释放锁,继续等待下一轮。注意要在修改变量之前加锁,避免并发修改导致数据不一致。 最后记得要调用 `pthread_join` 等待子线程结束。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值