首页 / 操作系统 / Linux / Java 线程编码之霓虹灯的实现
Java线程的实现通常要继承Thread类或者是实现接口Runnable的run方法即可。相关阅读: Java Hashtable多线程操作遍历问题 http://www.linuxidc.com/Linux/2013-01/78574.htmJava多线程顺序执行 http://www.linuxidc.com/Linux/2012-07/65033.htmJava多线程问题之同步器CyclicBarrier http://www.linuxidc.com/Linux/2012-07/64593.htmJava多线程之wait()和notify() http://www.linuxidc.com/Linux/2012-03/57067.htmJava多线程之synchronized http://www.linuxidc.com/Linux/2012-03/57068.htmJava多线程之并发锁 http://www.linuxidc.com/Linux/2012-03/57069.htm 实现代码如下:package com.Android.test;import java.awt.Color; import java.util.Random;import javax.swing.JFrame; import javax.swing.JLabel;public class NeonLight extends JFrame{ private static final long serialVersionUID = 5246470000332954366L; public JLabel[] label = {new JLabel("TAG-1"), new JLabel("TAG-2"), new JLabel("TAG-3"), new JLabel("TAG-4"), new JLabel("TAG-5"), new JLabel("TAG-6"), new JLabel("TAG-7")}; public Color[] color = {Color.BLACK, Color.BLUE, Color.YELLOW, Color.GRAY, Color.PINK, Color.GREEN, Color.ORANGE, Color.RED}; public NeonLight() { // TODO Auto-generated constructor stub setSize(500, 800); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setLayout(new FlowLayout()); setLayout(null); getContentPane().add(label[0]); label[0].setBounds(0,5,500,100); //设置组件JLabel不透明,只有设置为不透明,设置背景色才有效 label[0].setOpaque(true); getContentPane().add(label[1]); label[1].setBounds(0,5+100,500,100); label[1].setOpaque(true); getContentPane().add(label[2]); label[2].setBounds(0,5+200,500,100); label[2].setOpaque(true); getContentPane().add(label[3]); label[3].setBounds(0,5+300,500,100); label[3].setOpaque(true); getContentPane().add(label[4]); label[4].setBounds(0,5+400,500,100); label[4].setOpaque(true); getContentPane().add(label[5]); label[5].setBounds(0,5+500,500,100); label[5].setOpaque(true); getContentPane().add(label[6]); label[6].setBounds(0,5+600,500,100); label[6].setOpaque(true); setVisible(true); } //通过内部类实现霓虹灯任务类 class ColorVariance implements Runnable{ public void run() { while (true) { try { // 设置灯闪烁的频率 Thread.sleep(200); } catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } for (int i = 0; i < label.length; i++) { // 随机设置背景颜色 label[i].setBackground(color[new Random().nextInt(7)]); } } } } public static void main(String [] args){ NeonLight neonL = new NeonLight(); // 创建线程,注入霓虹灯任务 Thread ted = new Thread(neonL.new ColorVariance() ); // 开始闪烁 ted.start(); } }运行结果如下:本文永久更新链接地址 :http://www.linuxidc.com/Linux/2014-05/101045.htm
收藏该网址