New numerical simulations of the formation of the giant planets are presented, in which for the first time both the gas and planetesimal accretion rates are calculated in a self-consistent, interactive fashion. The simulations combine three elements: (1) three-body accretion cross sections of solids onto an isolated planetary embryo, (2) a stellar evolution code for the planet's gaseous envelope, and (3) a planetesimal dissolution code within the envelope, used to evaluate the planet's effective capture radius and the energy deposition profile of accreted material. Major assumptions include: The planet is embedded in a disk of gas and small planetesimals with locally uniform initial surface mass density, and planetesimals are not allowed to migrate into or out of the planet's feeding zone.All simulations are characterized by three major phases. During the first phase, the planet's mass consists primarily of solid material. The planetesimal accretion rate, which dominates that of gas, rapidly increases owing to runaway accretion, then decreases as the planet's feeding zone is depleted. During the second phase, both solid and gas accretion rates are small and nearly independent of time. The third phase, marked by runaway gas accretion, starts when the solid and gas masses are about equal. It is engendered by a strong positive feedback on the gas accretion rates, driven by the rapid contraction of the gaseous envelope and the rapid expansion of the outer boundary, which depends on the planet's total mass. The overall evolutionary time scale is generally determined by the length of the second phase. The actual rates at which the giant planets accreted small planetesimals is probably intermediate between the constant rates assumed in most previous studies and the highly variable rates used here. Within the context of the adopted model of planetesimal accretion, the joint constraints of the time scale for dissipation of the solar nebula and the current high-Zmasses of the giant planets lead to estimates of the initial surface density (σinit) of planetesimals in the outer region of the solar nebula. The results show that σinit≈ 10 g cm-2near Jupiter's orbit and that σinit∝a-2, whereais the distance from the Sun. These values are a factor of 3 to 4 times as high as that of the "minimum-mass" solar nebula at Jupiter's distance and a factor of 2 to 3 times as high at Saturn's distance. The estimates for the formation time of Jupiter and Saturn are 1 to 10 million years, whereas those for Uranus fall in the range 2 to 16 million years. These estimates follow from the properties of our Solar System and do not necessarily apply to giant planets in other planetary systems.