Java_多线程基础实践

开发一个窗体,窗体中有两个按钮,一个是开始,一个是结束。

用户点击“开始”在控制台持续输出一段话。点击“结束”则结束打印

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;


public class TestThread extends JFrame{
	
		boolean isContinue = true;					//线程是否继续的标志
		Container container=getContentPane();
		final String string="this,is,Java";
		JButton comeonButton=new JButton("开始");
		JButton comeoutButton=new JButton("结束");
		
	public TestThread(){
		
		
		container.setLayout(null);
		comeonButton.setBounds(36, 105, 82, 30);;
		comeoutButton.setBounds(160, 108, 100, 31);
		container.add(comeonButton);
		container.add(comeoutButton);
		//窗体结构
		
		
		final Thread t1;						//线程
		
		t1=new Thread(new Runnable() {
			
			public void run() {
				while(isContinue == true){
					System.out.println(string);
					try{
						Thread.sleep(1000);
					}
					catch(Exception e){
						e.printStackTrace();
					}
				}
				
			}		
		});						                //线程具体实现
		
		
		//以下为两个控件的点击事件
		
		comeonButton.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent arg0) {
				
				t1.start();
			} 
		})
		;
		comeoutButton.addActionListener(new ActionListener() {
		
			
			
			public void actionPerformed(ActionEvent arg0) {
				
				isContinue = false;
				System.out.println("线程停止不再继续输出");
			}
		})
		;	
	}

	public static void main(String[] args) {	
		TestThread.init(new TestThread(), 300, 300);
	}
	
	public static void init(TestThread print,int width,int height){
		print.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		print.setSize(width,height);
		print.setVisible(true);
}


}

运行如下:


发布了36 篇原创文章 · 获赞 26 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_36812792/article/details/80091946