में स्लीप विकल्प मुझे बताया गया है कि Thread.Sleep()
का उपयोग करना एक खराब समाधान है जब कोई सिंक्रनाइज़ विधि में कार्यों के लूप के भीतर कुछ समय अंतराल बनाना चाहता है।थ्रेड। जावा
दूसरी तरफ, मेरे पास दो अलग-अलग धागे हैं जो मेरे प्रोग्राम के चलने वाले समय में सक्रिय हैं और एक साझा ऑब्जेक्ट भी सक्रिय हैं और जब मैं उस साझा ऑब्जेक्ट में ऑब्जेक्ट.वाइट (लम्बा) का उपयोग करता हूं, तो यह मेरे जीयूआई को स्थिर करता है कुछ समय के लिए।
इस समस्या के लिए बेहतर समाधान क्या होगा?
अद्यतन कोड का यह हिस्सा धागे जो जीयूआई में शुरू हो रहा है में से एक सहित जाता है:
class temperatureUp extends Thread { @Override public void run() { while(true) { try { GBC.increaseTemp(); updateSystemStatus(); } catch(Exception ex) { StringWriter w = new StringWriter(); ex.printStackTrace(new PrintWriter(w)); txtLog.setText(w + "\n" + txtLog.getText()); } } } };
और इस साझा वस्तु में सिंक्रनाइज़ विधि, जीबीसी है:
public synchronized void increaseTemp() throws InterruptedException{
// don't increase the temperature if the boiler
// is not turned on...
while (!isBoilerOn)
wait();
// increase the current temperature
if ((currentTemp + 1) < MAX_TEMP && currentTemp < desiredTemp) {
Thread.sleep(2000); ///what should put here if not thread sleep?
currentTemp ++;
updateGasBoilerStatus();
}
}
आप [घटना भेजने धागा] (http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html) प्रतीक्षा करनी पड़ सकती किया जाना चाहिए। क्या आप अपने धागे को कैसे शुरू करते हैं और जब आप प्रतीक्षा() कॉल करते हैं, तो कोड में एक छोटा सा उदाहरण प्रदान कर सकते हैं? – theon
पर एक नजर डालें [ 'SwingWorker'] (http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html)। साथ ही, यह जानने के लिए ['this answer'] (http://stackoverflow.com/a/11546203/597657) देखें। –
@theon मैंने पोस्ट को अपडेट किया और कोड के कुछ हिस्से को जोड़ा। – Afflatus