Work子函数与主函数调用

在这里插入图片描述
在这里插入图片描述

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>

void change(int* p)//相当于p=&i,*&i等价于i
{
	*p = *p / 2;

}

int main() {
	int i;
	scanf("%d", &i);
	change(&i);
	printf("%d\n", i);

}


### Java 中阻塞主函数或主线程的实现方式 在 Java 中,可以通过多种方式来阻塞 `main` 函数或者主线程。以下是常见的几种方法: #### 1. 使用 `Thread.join()` 方法 通过调用另一个线程对象的 `join()` 方法,可以让当前线程(这里是主线程)等待直到目标线程完成运行。这通常用于协调多个线程之间的执行顺序。 ```java public class Main { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(() -> { try { Thread.sleep(5000); // Simulate some work System.out.println("Worker thread finished."); } catch (InterruptedException e) { e.printStackTrace(); } }); thread.start(); // Start the worker thread thread.join(); // Block until the worker thread finishes System.out.println("Main thread continues after join()."); } } ``` 这种方法会使得主线程被阻塞,直到子线程结束为止[^2]。 --- #### 2. 使用 `Object.wait()` 和同步机制 如果希望让主线程进入休眠状态并等待某个条件满足后再继续执行,可以使用 `wait()`/`notify()` 或者更现代的 `Condition` 类来进行控制。 ```java public class Main { private static final Object lock = new Object(); public static void main(String[] args) throws InterruptedException { synchronized (lock) { System.out.println("Main thread is waiting..."); lock.wait(); // Blocks here indefinitely or until notified. System.out.println("Main thread was notified and unblocked!"); } } public static void notifyMainThread() { synchronized (lock) { lock.notifyAll(); // Unblocks all threads that are waiting on this object's monitor. } } } ``` 此代码片段展示了如何使主线程暂停,并由外部逻辑通知其恢复工作[^3]。 --- #### 3. 利用 I/O 操作中的阻塞行为 某些输入输出流具有天然的阻塞特性,比如读取文件、网络套接字等。这些操作会在数据未准备好之前挂起调用它们的线程。 ```java import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter something to continue: "); String input = reader.readLine(); // This call blocks execution till user enters data. System.out.println("You entered: " + input); } } ``` 在这种情况下,程序将停留在 `readLine()` 调用处直至有可用的数据到达标准输入设备[^5]。 --- #### 4. 借助计时器或其他延迟手段 有时我们可能只是想单纯延缓一段时间再往下走,则可以直接采用睡眠指令达成目的;不过需要注意的是这种做法并不真正构成所谓意义上的“阻塞”,因为它并没有涉及到任何事件驱动型的通知过程。 ```java public class Main { public static void main(String[] args) throws InterruptedException { long startTime = System.currentTimeMillis(); while ((System.currentTimeMillis() - startTime) < 10 * 1000L){ // Do nothing, just keep checking time elapsed every cycle of loop body... } System.out.println("Slept enough! Exiting now..."); } } ``` 上述例子中展示了一种基于轮询的时间消耗策略,虽然简单粗暴但却有效实现了类似效果[^1]。 --- ### 总结 以上介绍了四种不同的技术途径用来达到阻塞 Java 应用程序入口点的目的——即延长甚至无限期维持住整个应用程序生命周期的行为模式。每一种都有各自适用范围以及优缺点所在,在实际开发过程中应当依据具体需求选取最合适的解决方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值