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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值