Java学习--线程:用按钮控制线程的开始和暂停

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;
					}	
				}	
			}
		}	
	}
}

你可能感兴趣的:(Java学习--线程:用按钮控制线程的开始和暂停)