Fix flaky tests in test_weakref and test_weakset

Weak reference callbacks are called by a separate reaper thread,
therefore tests have to be sensitive to possible races. Although
arguably making this more robust by appropriate interleaving of
gc.collect() and time.sleep() is not good enough, these tests are as
good as we can make without making them more JVM dependent.