Java多线程实现窗口背景颜色轮换(synchronize加锁)

来源:互联网 发布:天窗用处大吗 知乎 编辑:程序博客网 时间:2024/05/16 18:30

最近学校请外面老师来上课,给我们巩固了一些Java基础,并写了这个多线程实现窗口轮换背景,我加了wait()和notifyAll()方法。不过时间延迟上有一点点问题,希望与大家共勉,以下是贴的代码:

package com.ex;import java.awt.Color;import javax.swing.JFrame;import javax.swing.JPanel;public class PrintColor extends JFrame{private static JPanel panel;private static boolean b; public PrintColor(){this.setBounds(200, 200, 200, 200);this.setTitle("我是窗口");b = false;panel = (JPanel) this.getContentPane();//panel.setBackground(Color.GREEN);}public static void main(String[] args) {// TODO Auto-generated method stubfinal PrintColor printColor = new PrintColor();//Thread thread = new Thread(printColor);//thread.start();new Thread(new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){synchronized (printColor) {if(!b){try {printColor.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}panel.setBackground(Color.GREEN);System.out.println(Thread.currentThread().getName());b = true;printColor.notifyAll();}}}}).start();new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){synchronized (printColor) {if(b){try {printColor.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}panel.setBackground(Color.RED);System.out.println(Thread.currentThread().getName());b = false;printColor.notifyAll();}}}}).start();printColor.setVisible(true);}
ps:整理自己所写的代码真的很重要。活到老学到老吧!