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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章