Java 학습-스레드:스레드의 시작 및 일시 중지를 버튼으로 제어

13272 단어

wait 및 notify

  • 코드
  • this가 아닌 라인의 이름으로 현을 통제하다

    코드

    package inheritance;
    
     
    
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    
    import javax.swing.*;
    
    public class ThreadPrintTest extends JFrame{
    	boolean suspended=false;
    	JTextArea jt=new JTextArea();	
    	final JButton jb=new JButton("  ");
    	final JButton jb2=new JButton("  ");
    	Thread thread1=null;
    		
    	public ThreadPrintTest() {
    		super();
    		Container c=getContentPane();
    		setLayout(new FlowLayout(2,10,10));
    		jt.setSize(100,100);
    		jt.setLineWrap(true);
    		c.add(jt);
    		c.add(jb);
    		c.add(jb2);
    		
    		jb.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {				
    				if(thread1==null) {
    					thread1=new Thread(new MyThread());
    					thread1.start();
    				}
    				else {					
    					synchronized(thread1) {               
    						thread1.notify();                   
    	                }
    					suspended = false;					
    				}
    				
    			}
    		});
    		jb2.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {				
    				suspended = true;			
    			}
    		});		
    	}
    	public static void main(String [] args) {
    		init(new ThreadPrintTest(),300,200);
    	}
    	public static void init(JFrame frame,int width,int height) {
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setSize(width, height);
    		frame.setVisible(true);
    	}
    	
    	private final class MyThread implements Runnable{
    		
    		public void run() {
    			while(true) {
    				jt.append("  !");
    				synchronized (thread1) {
    					try {
    							Thread.sleep(1000);
    							if(suspended) {
    								thread1.wait();
    							}
    					}catch(InterruptedException e) {
    						System.out.println("       ");
    						break;
    					}	
    				}	
    			}
    		}	
    	}
    }
    
    

    좋은 웹페이지 즐겨찾기