D.Tech Academic
Deep Singh
Pages
Core Java
Web App
Spring
Hibernate
Kotlin
Android
Python
Flutter
Spring Boot
Simple wait and notify example
wait and notify example with GUI components
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; class Resource { int nums[] = new int[10]; int count = 0; int i; String text = ""; synchronized void waitThread(JTextArea ta, int num) { for (i = 1; i <= nums.length; i++) { nums[count++] = num * i; try { text = text + num + " * " + " = " + nums[count - 1] + "\n"; ta.setText(text); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized int getCount() { return count; } synchronized void notifyThread() { notify(); } } public class D1 { JLabel l1; Resource resource = new Resource(); public D1() { JFrame f = new JFrame(); f.setSize(500, 500); f.setLayout(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton b1 = new JButton("start"); JButton b3 = new JButton("notify"); JTextArea ta = new JTextArea(); JScrollPane jp=new JScrollPane(ta); jp.setBounds(100, 150, 300, 200); b1.setBounds(20, 30, 100, 30); b3.setBounds(20, 110, 100, 30); f.add(jp); f.add(b1); f.add(b3); b1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Thread t1 = new Thread() { @Override public void run() { resource.waitThread(ta, 12); } }; t1.start(); b1.setEnabled(false); b3.setEnabled(true); }catch (Exception e1) { // TODO: handle exception } } }); b3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { if(resource.getCount()!=10) { System.out.println(resource.getCount()); Thread t1 = new Thread() { @Override public void run() { resource.notifyThread(); } }; t1.start(); }else { resource.count=0; ta.setText(""); resource.text=""; b3.setEnabled(false); b1.setEnabled(true); } }catch (Exception e1) { // TODO: handle exception } } }); f.setVisible(true); } public static void main(String[] args) { D1 d = new D1(); } }
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment