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

最近学校请外面老师来上课,给我们巩固了一些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 stub
		final PrintColor printColor = new PrintColor();
		//Thread thread = new Thread(printColor);
		//thread.start();
		
		new Thread(new Runnable(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(true){
					synchronized (printColor) {
						if(!b){
							try {
								printColor.wait();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						panel.setBackground(Color.GREEN);
						System.out.println(Thread.currentThread().getName());
						b = true;
						printColor.notifyAll();
					}
				}
			}
			
		}).start();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(true){
					synchronized (printColor) {
						if(b){
							try {
								printColor.wait();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						panel.setBackground(Color.RED);
						System.out.println(Thread.currentThread().getName());
						b = false;
						printColor.notifyAll();
					}
				
				}
			}
		}).start();
	
		printColor.setVisible(true);
	}

ps:整理自己所写的代码真的很重要。活到老学到老吧!

    原文作者:java锁
    原文地址: https://blog.csdn.net/m0_37672234/article/details/73511850
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞