📄 nodeframe.java
字号:
/*
* Created on 2005-9-3
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.apollo.thread.example;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.Timer;
public class NodeFrame extends JFrame {
private final Node node;
private static Point location = new Point(0,0);
private static final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
public NodeFrame(Node node){
this.node = node;
Container container = this.getContentPane();
container.setLayout(new BorderLayout());
container.add(new JLabel("处理 " + this.node + " 节点"), BorderLayout.NORTH);
container.add(new JLabel("随机值为:" + this.node.getData()), BorderLayout.SOUTH);
final JTextField msg = new JTextField("开始处理!");
msg.setEditable(false);
msg.setBackground(Color.ORANGE);
container.add(msg, BorderLayout.CENTER);
ActionListener timeListener = new ActionListener(){
int i = 0;
public void actionPerformed(ActionEvent e) {
i++;
msg.setText("已完成 " + i + "%");
if (i==100) {
((Timer)e.getSource()).stop();
synchronized (NodeFrame.this.node) {
msg.setBackground(Color.BLUE);
msg.setForeground(Color.WHITE);
msg.setText("数据接收完毕!");
NodeFrame.this.node.notify();
}
}
}
};
int delay = ((this.node.getData() * 100) % 300) + 1;
Timer t = new Timer(delay,timeListener);
t.start();
this.setTitle("线程名:" + Thread.currentThread().getName());
this.setSize(100,100);
synchronized (location) {
this.setLocation(location);
//把这句放在同步块以外会导致窗口重叠!
//注:把有关联性、有原子性的一组代码放在同步块中,但不要什么语句都向里面放,这样
// 会无谓的加长对象锁定的时间,影响多线程的效率!
nextLocation();
}
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.show();
}
/**
* 算出下一个NodeFrame的Location值
* 注:如果不加synchronized将会随机出现NodeFrame叠加在一起的情况
*/
private static synchronized void nextLocation(){
if (location.x + 123*2 >= screenSize.width){
location.x = 0;
location.y += 100;
}else{
location.x += 123;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -