Two-dimensional (2D) materials are considered to be promising candidates for constructing revolutionary electronic devices. However, difficulties in controlling the polarity, concentration, and spatial distribution of charge carriers in 2D materials make the construction of 2D p–n junctions rather challenging. Here, we report the successful construction of ultrafast-programmable 2D p–n homojunctions with a semi-floating-gate configuration based on a vertically stacked molybdenum disulfide (MoS2)/hexagonal boron nitride/multilayer graphene van der Waals heterostructure. By partially electrostatically doping the MoS2 channel under different control-gate voltage pulses, three types of 2D homojunctions, including p–n, n+–n, and n–n, can be constructed. The 2D p–n homojunction can be programmed at an ultrafast speed of within 160 ns and exhibits a large rectification ratio of ∼104. Based on a modified Shockley equation, an ideality factor of ∼2.05 is extracted, indicating that the recombination process dominated the transport mechanism. The MoS2 2D p–n homojunction shows a maximum electrical power conversion efficiency of up to 2.66% under a weak light power of 0.61 nW and a high photovoltage responsivity of 5.72 × 109 V W−1. These results indicate that the ultrafast-programmable 2D p–n homojunction has great potential for use in high-performance photovoltaics and optoelectronics.