A subway rider shot two police officers who caught him walking between cars in Brooklyn Thursday, and the suspect was killed in the exchange of gunfire, officials say.

The cops were the second and third NYPD officers to be shot in the same evening.

The officers, Lukasz Kozicki and Michael Levay, stopped the suspect on a Manhattan-bound N train as it approached the Fort Hamilton Parkway stop in Dyker Heights after he was caught walking between subway cars, Mayor Bloomberg said at a press conference. Both cops, assigned to the transit division, were in plain clothes.

When asked for identification, the suspect acted as if to comply but then pulled out a 9 mm Taurus and opened fire on the officers, Bloomberg said. Levay, 27, was hit in the lower back and Kozicki, 32, was hit three times: once in each thigh and once in the groin. Levay was able to return fire, killing the suspect.

One passenger was grazed in the gun battle and wasn't seriously hurt, said Police Commissioner Ray Kelly. Other passengers on the train were able to flee onto the platform when the gunfire erupted. Neither the platform nor the train was crowded at the time.

Kozicki and Levay were taken to Lutheran Medical Center, where they are in stable condition.

The unidentified suspect had a past criminal record of five assaults, including one with a knife, officials said.

Earlier Thursday evening, an off-duty officer was shot in the Bronx during an apparent robbery attempt, marking three officers shot on day 3 of 2013. In all of 2012, 12 officers were shot, according to Bloomberg.

"Sometimes the good guys get shot, and sometimes they are killed," Bloomberg said. "Tonight, thank God, three good guys -- three New York City police officers who acted heroically -- are going to make it."

Bloomberg's "good guys with guns" remark was an apparent retort to the National Rifle Association's recent statement that "the only thing that stop a bad guy with a gun is a good guy with a gun." The mayor has been a vocal advocate for tighter gun control.

The Brooklyn-bound N train was bypassing the station Thursday night. The northbound train was running the line between Stillwell Avenue and 36th Street.