⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 example09_threads.java

📁 这是我java课程第九章的作业,也是实现多线程的技术.
💻 JAVA
字号:
package example.ch09;

import java.awt.*;
import javax.swing.*;

public class Example09_Threads extends JFrame
{
	JLabel dispDigit;
	JPanel dispColor;
	
	public Example09_Threads()
	{
		super("Threads");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		dispDigit = new JLabel("disp digit(1 - 10)", JLabel.CENTER);
		dispDigit.setFont(new Font("黑体", Font.BOLD, 32));
		dispColor = new JPanel();
		dispColor.setBorder(BorderFactory.createLineBorder(Color.RED, 2));
		
		Container con = getContentPane();
		con.add(dispDigit, "North");
		con.add(dispColor, "Center");
		
		setSize(300,300);
		
		this.setLocationRelativeTo(null);

		setVisible(true);
		
		new DispDigit(dispDigit).start();
		new Thread(new DispColor(dispColor)).start();
	}
	
	public static void main(String[] args)
	{
		new Example09_Threads();
	}
}

class DispDigit extends Thread
{
	JLabel label;
	int i = 1;
	
	public DispDigit(JLabel label)
	{
		this.label = label;
	}
	
	public void run()
	{
		while (true)
		{
			try
			{
				label.setText("" + i);
				i++;
				if (i > 10) i = 1;
				Thread.sleep(1000);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}
}

class DispColor implements Runnable
{
	JPanel panel;
	
	public DispColor(JPanel panel)
	{
		this.panel = panel;
	}
	
	public void run()
	{
		while (true)
		{
			try
			{
				int r = (int)(Math.random() * 255);
				int g = (int)(Math.random() * 255);
				int b = (int)(Math.random() * 255);
				panel.setBackground(new Color(r, g, b));
				Thread.sleep(2000);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}
}		}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -