天天看点

Swing后台工作线程

Swing后台工作线程的各种启动方式测试,其中有些不能启动后台工作线程,在注释中有标注。

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * @Description: 多种方式启动界面的工作线程。
 * https://blog.csdn.net/L141210113/article/details/83933526
 * @author       wzjin
 * @date         2020年5月4日 上午10:00:42
 */
public class Swing后台工作线程
{
	private JFrame frame;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args)
	{
		EventQueue.invokeLater(new Runnable()
		{
			public void run()
			{
				try
				{
					Swing后台工作线程 window = new Swing后台工作线程();
					window.frame.setVisible(true);
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		});
	}
	/**
	 * Create the application.
	 */
	public Swing后台工作线程()
	{
		frame = new JFrame();
		frame.setBounds(158, 158, 268, 158);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JButton btnNewButton = new JButton("点击我");
		btnNewButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				//-----------------------------------------普通线程方式
//				new Thread()
//				{
//					@Override
//					public void run()
//					{
//						 无限循环();
//					}
//				}.start();
				//-----------------------------------------lamdba方式
				new Thread(() ->无限循环()).start();
				//-----------------------------------------//工作线程方式
//				SwingWorker<Void, Integer> swingWorker = new SwingWorker<Void, Integer>()
//				{
//					@Override
//					protected Void doInBackground() throws Exception
//					{
//						无限循环();
//						return null;
//					}
//				};
//				swingWorker.execute();
				//-----------------------------------------这种方式不能启动后台线程
//				javax.swing.SwingUtilities.invokeLater(new Runnable() 
//				{
//					public void run()
//					{
//						无限循环();
//					}
//				});
				//-----------------------------------------这种方式不能启动后台线程
//				javax.swing.SwingUtilities.invokeLater(() ->无限循环());
				//-----------------------------------------这种方式不能启动后台线程
//				RunnableFuture<Object> rf = new FutureTask<Object>(new Callable<Object>()
//				{//这种方式看起来是派发线程了,但是界面还是卡死
//					@Override  
//					public Object call() throws Exception
//					{
//						无限循环();
//						return null;
//					}
//				});
//				SwingUtilities.invokeLater(rf);
			}
		});
		frame.getContentPane().add(btnNewButton, BorderLayout.NORTH);
	}
	private void 无限循环()
	{
		int i = 0;
		while (true)
		{
			try
			{
				Thread.sleep(100);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			System.out.println(i++);
		}
	}
}