JAVA例13)マルチスレッドプログラミング(3)
58160 ワード
スレッド適用インスタンス
実例244雪の村
実例245小飛侠
例246飛流直下
インスタンス247マルチスレッドブレークポイント再送
例248スクロールビーズ
インスタンス249残高照会
インスタンス250のスクロール文字
例251フローティング効果
インスタンス252メモリの使用状況を監視する
例253きらきら光る星空
例254銀行とスーパー業務のシミュレーション
実例244雪の村
package Chapter17;
import java.applet.Applet;
import java.awt.*;
import java.util.Random;
public class SnowVillage extends Applet implements Runnable {
Thread thread;//
Image off, images[];//
Random random;//
int flag, sonwNum, wind, thread_1, size;// int
int[] X, Y;// int , X Y
long time = 0;//
Dimension ds;// Dimension
MediaTracker mt;// MediaTracker
int getValue(String s1, int s2, int max, int min) {// HTML
String s = getParameter(s1);
if (s != null) {
if ((s2 = Integer.parseInt(s)) > max)
return max;
else if (s2 < min)
return min;
else
return s2;
} else
return s2;
}
public void init() {// Applet
this.setSize(300, 200);
random = new Random();
ds = getSize();
off = createImage(ds.width, ds.height);//
sonwNum = getValue("sonwNum", 100, 500, 0);//
size = getValue("size", 3, 10, 3);//
thread_1 = getValue("threadsleep", 80, 1000, 10);//
// XY
X = new int[sonwNum];
Y = new int[sonwNum];
for (int i = 0; i < sonwNum; i++) {
X[i] = random.nextInt() % (ds.width / 2) + ds.width / 2;
Y[i] = random.nextInt() % (ds.height / 2) + ds.height / 2;
}
mt = new MediaTracker(this);
images = new Image[1];
images[0] = getImage(getDocumentBase(), "xue.jpg");
mt.addImage(images[0], 0);
try {
mt.waitForID(0);
} catch (InterruptedException _ex) {
return;
}
flag = 0;
}
public void start() {//
if (thread == null) {
thread = new Thread(this);
thread.start();//
}
}
public void stop() {//
thread = null;
}
public void run() {//
while (thread != null) {
try {
Thread.sleep(thread_1);
} catch (InterruptedException _ex) {
return;
}
repaint();
}
}
public void snow(Graphics g) {//
g.setColor(Color.white);
for (int i = 0; i < sonwNum; i++) {
g.fillOval(X[i], Y[i], size, size);
X[i] += random.nextInt() % 2 + wind;
Y[i] += (random.nextInt() % 6 + 5) / 5 + 1;
if (X[i] >= ds.width)
X[i] = 0;
if (X[i] < 0)
X[i] = ds.width - 1;
if (Y[i] >= ds.height || Y[i] < 0) {
X[i] = Math.abs(random.nextInt() % ds.width);
Y[i] = 0;
}
}
wind = random.nextInt() % 5 - 2;
}
public void paint(Graphics g) {//
off.getGraphics().setColor(Color.black);
off.getGraphics().fillRect(0, 0, ds.width, ds.height);
off.getGraphics().drawImage(images[0], 0, 0, this);
snow(off.getGraphics());
g.drawImage(off, 0, 0, null);
}
public void update(Graphics g) {//
paint(g);
}
}
実例245小飛侠
package Chapter17.example;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
public class SplitLine extends Applet implements Runnable {
private Image moveleft__1, moveright_1, moveleft_2, moveright_2, temp;// Image
private Image image;//
private Graphics graphics;
private Thread thread = null;
private MediaTracker img_tracker;
private int height, width;
public void init() {// Applet
// Image
moveright_1 = getImage(getDocumentBase(), "3.jpg");
moveright_2 = getImage(getDocumentBase(), "4.jpg");
moveleft__1 = getImage(getDocumentBase(), "1.jpg");
moveleft_2 = getImage(getDocumentBase(), "2.jpg");
// MediaTracker
img_tracker = new MediaTracker(this);
//
img_tracker.addImage(moveright_1, 0);
img_tracker.addImage(moveleft__1, 0);
img_tracker.addImage(moveright_2, 0);
img_tracker.addImage(moveleft_2, 0);
// Applet
width = this.size().width;
height = this.size().height;
try {
img_tracker.waitForID(0);// ID
} catch (InterruptedException e) {
}
//
image = createImage(width, height);
// Graphics
graphics = image.getGraphics();
}
public void start() {// Applet start
if (thread == null) {
thread = new Thread(this);
thread.start();//
}
}
public void run() {// run
Color fg = this.getForeground();
int imgWidth, imageHeight, x = 0, y = 0;
boolean forward = true;
imgWidth = moveright_1.getWidth(this);
imageHeight = moveright_1.getHeight(this);
y = (height - imageHeight) / 2;
fg = Color.blue;//
try {
while (thread != null) {
thread.sleep(200);
if (forward) {
x += 15;
if ((x % 2) == 1) {
temp = moveright_1;
} else {
temp = moveright_2;
}
if (x >= (width - imgWidth)) {
forward = false;
}
} else {
x -= 15;
if ((x % 2) == 1) {
temp = moveleft__1;
} else {
temp = moveleft_2;
}
if (x == 0) {
forward = true;
}
}
graphics.setColor(Color.white);//
graphics.fillRect(0, 0, width, height);
graphics.setColor(fg.brighter().darker());
graphics.drawLine(0, (height - imageHeight) / 2 + imageHeight,
width, (height - imageHeight) / 2 + imageHeight);
graphics.setColor(fg.darker().brighter());
graphics.drawLine(0, (height - imageHeight) / 2 + imageHeight,
width, (height - imageHeight) / 2 + imageHeight);
graphics.drawImage(temp, x, y, this);
repaint();
}
} catch (InterruptedException e) {
}
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
}
例246飛流直下
package Chapter17.status;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
public class Faucet extends Applet implements Runnable {
final int Max = 1000;//
Drop d[];//
int width, height, X, Y;// Applet , XY
Image off;//
Graphics graphics;// Graphics
Thread thread;//
public void init() {// Applet
this.setSize(300, 200);
setBackground(Color.gray);
width = getSize().width;
height = getSize().height;
d = new Drop[Max];
for (int i = 0; i < Max; i++)
d[i] = new Drop();
off = createImage(width, height);
graphics = off.getGraphics();
}
public void start() {//
thread = new Thread(this);
thread.start();
}
public void stop() {//
thread = null;
}
public void update(Graphics g) {//
paint(g);
}
public void paint(Graphics g) {//
g.drawImage(off, 0, 0, this);
}
public void run() {//
boolean reset = false;
int i, t = 0;
while (true) {
graphics.clearRect(0, 0, width, height);
graphics.setColor(Color.white);
graphics.drawLine(0, 15, 10, 15);
for (i = 0; i < Max; i++) {
graphics.fillOval((int) d[i].X, (int) d[i].Y, 3, 3);
d[i].X = d[i].X + d[i].newX;
if (d[i].X > 10) {
d[i].Y += d[i].newY * d[i].time / 1000;
d[i].newY = (int) 9.8 * d[i].time;
d[i].time++;
}
if (d[i].Y > height) {
d[i].reset();
}
}
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
}
class Drop {//
double X, Y;
double newX, newY;
int time;
public Drop() {
reset();
}
public void reset() {//
X = (int) (Math.random() * -40);
Y = (int) (Math.random() * 5 + 10);
newX = Math.random() * 3 + 1.0;
newY = 0;
time = 0;
}
}
インスタンス247マルチスレッドブレークポイント再送
package Chapter17.download;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
//Java , Web , 。
public class ResumeUpload {
private String downSource = "http://kent.dl.sourceforge.net/sourceforge/jamper/Sample.zip"; // Web
private String savePath = "d:\\temp"; //
private String saveName = " YY .zip"; //
public ResumeUpload() {
try {
FileInfo bean = new FileInfo(downSource, savePath, saveName, 5);
FTPthread fileFetch = new FTPthread(bean);
fileFetch.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ResumeUpload();
}
}
class FTPthread extends Thread { //
FileInfo siteInfoBean = null; // Bean
long[] nPos;
long[] startPos; //
long[] endPos; //
FilePart[] fileSplitterFetch; //
long nFileLength; //
boolean bFirst = true; //
boolean bStop = false; //
File tmpFile; //
DataOutputStream output; //
public FTPthread(FileInfo bean) throws IOException {
siteInfoBean = bean;
tmpFile = new File(bean.getSFilePath() + File.separator
+ bean.getSFileName() + ".info");
if (tmpFile.exists()) {
bFirst = false;
readInform();
} else {
startPos = new long[bean.getNSplitter()];
endPos = new long[bean.getNSplitter()];
}
}
public void run() {
//
//
// PartCacth
// PartCacth
//
try {
if (bFirst) {
nFileLength = getFileSize();
if (nFileLength == -1) {
System.err.println("File Length is not known!");
} else if (nFileLength == -2) {
System.err.println("File is not access!");
} else {
for (int i = 0; i < startPos.length; i++) {
startPos[i] = (long) (i * (nFileLength / startPos.length));
}
for (int i = 0; i < endPos.length - 1; i++) {
endPos[i] = startPos[i + 1];
}
endPos[endPos.length - 1] = nFileLength;
}
}
//
fileSplitterFetch = new FilePart[startPos.length];
for (int i = 0; i < startPos.length; i++) {
fileSplitterFetch[i] = new FilePart(siteInfoBean.getSSiteURL(),
siteInfoBean.getSFilePath() + File.separator
+ siteInfoBean.getSFileName(), startPos[i],
endPos[i], i);
AddInform.log("Thread " + i + " , = " + startPos[i]
+ ", = " + endPos[i]);
fileSplitterFetch[i].start();
}
//
// int count = 0;
// while
boolean breakWhile = false;
while (!bStop) {
writeInform();
AddInform.sleep(500);
breakWhile = true;
for (int i = 0; i < startPos.length; i++) {
if (!fileSplitterFetch[i].bDownOver) {
breakWhile = false;
break;
}
}
if (breakWhile)
break;
}
System.out.println(" !");
} catch (Exception e) {
e.printStackTrace();
}
}
//
public long getFileSize() {
int nFileLength = -1;
try {
URL url = new URL(siteInfoBean.getSSiteURL());
HttpURLConnection httpConnection = (HttpURLConnection) url
.openConnection();
httpConnection.setRequestProperty("User-Agent", "NetFox");
int responseCode = httpConnection.getResponseCode();
if (responseCode >= 400) {
processErrorCode(responseCode);
return -2; // -2 Web
}
String sHeader;
for (int i = 1;; i++) {
sHeader = httpConnection.getHeaderFieldKey(i);
if (sHeader != null) {
if (sHeader.equals("Content-Length")) {
nFileLength = Integer.parseInt(httpConnection
.getHeaderField(sHeader));
break;
}
} else
break;
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
AddInform.log(nFileLength);
return nFileLength;
}
// ( )
private void writeInform() {
try {
output = new DataOutputStream(new FileOutputStream(tmpFile));
output.writeInt(startPos.length);
for (int i = 0; i < startPos.length; i++) {
output.writeLong(fileSplitterFetch[i].startPos);
output.writeLong(fileSplitterFetch[i].endPos);
}
output.close();
} catch (Exception e) {
System.out.println(" ");
}
}
// ( )
private void readInform() {
try {
DataInputStream input = new DataInputStream(new FileInputStream(
tmpFile));
int nCount = input.readInt();
startPos = new long[nCount];
endPos = new long[nCount];
for (int i = 0; i < startPos.length; i++) {
startPos[i] = input.readLong();
endPos[i] = input.readLong();
}
input.close();
//
for (int i = 0; i < startPos.length; i++) {
if (startPos[i] > endPos[i]) {
startPos[i] = endPos[i];
}
}
} catch (Exception e) {
System.out.println(" ");
}
}
private void processErrorCode(int nErrorCode) {
System.err.println("Error Code : " + nErrorCode);
}
//
public void doStop() {
bStop = true;
for (int i = 0; i < startPos.length; i++)
fileSplitterFetch[i].splitterStop();
}
}
class FileInfo { //
private String sSiteURL; // URL
private String sFilePath; //
private String sFileName; //
private int nSplitter; //
public FileInfo() {
this("", "", "", 5); //
}
public FileInfo(String sURL, String sPath, String sName, int nSpiltter) {
sSiteURL = sURL;
sFilePath = sPath;
sFileName = sName;
this.nSplitter = nSpiltter;
}
public String getSSiteURL() {
return sSiteURL;
}
public void setSSiteURL(String value) {
sSiteURL = value;
}
public String getSFilePath() {
return sFilePath;
}
public void setSFilePath(String value) {
sFilePath = value;
}
public String getSFileName() {
return sFileName;
}
public void setSFileName(String value) {
sFileName = value;
}
public int getNSplitter() {
return nSplitter;
}
public void setNSplitter(int nCount) {
nSplitter = nCount;
}
}
class FilePart extends Thread {
String sURL; //
long startPos; //
long endPos; //
int nThreadID; // ID
boolean bDownOver = false; //
boolean bStop = false; //
SaveFile fileAccess = null;
public FilePart(String sURL, String sName, long nStart, long nEnd, int id)
throws IOException {
this.sURL = sURL;
this.startPos = nStart;
this.endPos = nEnd;
nThreadID = id;
fileAccess = new SaveFile(sName, startPos);
}
public void run() {
while (startPos < endPos && !bStop) {
try {
URL url = new URL(sURL);
HttpURLConnection httpConnection = (HttpURLConnection) url
.openConnection();
httpConnection.setRequestProperty("User-Agent", "NetFox");
String sProperty = "bytes=" + startPos + "-";
httpConnection.setRequestProperty("RANGE", sProperty);
AddInform.log(sProperty);
InputStream input = httpConnection.getInputStream();
byte[] b = new byte[1024];
int nRead;
while ((nRead = input.read(b, 0, 1024)) > 0
&& startPos < endPos && !bStop) {
startPos += fileAccess.write(b, 0, nRead);
}
AddInform.log("Thread " + nThreadID + " is over!");
bDownOver = true;
} catch (Exception e) {
System.out.println(getName() + " ");
}
}
bDownOver = true;
}
public void logResponseHead(HttpURLConnection con) {
for (int i = 1;; i++) {
String header = con.getHeaderFieldKey(i);
if (header != null)
AddInform.log(header + " : " + con.getHeaderField(header));
else
break;
}
}
public void splitterStop() {
bStop = true;
}
}
class SaveFile implements Serializable { //
RandomAccessFile oSavedFile;
long nPos;
public SaveFile() throws IOException {
this("", 0);
}
public SaveFile(String sName, long nPos) throws IOException {
oSavedFile = new RandomAccessFile(sName, "rw");
this.nPos = nPos;
oSavedFile.seek(nPos);
}
public synchronized int write(byte[] b, int nStart, int nLen) {
int n = -1;
try {
oSavedFile.write(b, nStart, nLen);
n = nLen;
} catch (IOException e) {
System.out.println(" ");
}
return n;
}
}
class AddInform { // sleep
public AddInform() {
}
public static void sleep(int nSecond) {
try {
Thread.sleep(nSecond);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void log(String sMsg) {
System.out.println(sMsg);
}
public static void log(int sMsg) {
System.out.println(sMsg);
}
}
例248スクロールビーズ
package Chapter17;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MoveBall extends Frame implements ActionListener {
// 3 , 、
private Button quit = new Button(" ");
private Button start = new Button(" ");
private Button stop = new Button(" ");
private DrawBall balls[] = new DrawBall[20];
// ,
public MoveBall() {
super();
setLayout(new FlowLayout());
add(quit);
quit.addActionListener(this);
add(start);
start.addActionListener(this);
add(stop);
stop.addActionListener(this);
validate();
this.setBackground(Color.black);
this.setSize(300, 300);
this.setVisible(true);
for (int i = 0; i < balls.length; i++) {
int x = (int) (getSize().width * Math.random());
int y = (int) (getSize().height * Math.random());
balls[i] = new DrawBall(this, x, y);
}
}
public void actionPerformed(ActionEvent e) {// Button
if (e.getSource() == stop) {//
for (int i = 0; i < balls.length; i++) {
balls[i].setRun();
}
}
if (e.getSource() == start) {//
for (int i = 0; i < balls.length; i++) {
balls[i].setRun();
balls[i] = new DrawBall(this, balls[i].x, balls[i].y);
}
}
if (e.getSource() == quit) {//
System.exit(0);
}
}
public void paint(Graphics g) {//
for (int i = 0; i < balls.length; i++)
if (balls[i] != null)
balls[i].paintBall(g);
}
public static void main(String[] args) {//
MoveBall t = new MoveBall();
}
}
class DrawBall extends Thread {//
//
private int a = 2 * (1 - 2 * (int) Math.round(Math.random()));
private int b = 2 * (1 - 2 * (int) Math.round(Math.random()));
private boolean running = false;//
private MoveBall table = null;// MoveBall
protected int x, y;// XY
public DrawBall(MoveBall _table, int _x, int _y) {// ,
table = _table;
x = _x;
y = _y;
start();
}
public void start() {
running = true;
super.start();//
}
public void setRun() {
running = false;
}
public void run() {// Thread run
while (running) {
move();
try {
sleep(50);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
table.repaint();
}
}
public void paintBall(Graphics g) {//
g.setColor(Color.red);
g.fillOval(x, y, 20, 20);
}
private void move() {//
x += a;
y += b;
if ((x > table.getSize().width) || (x < 0)) {
a *= (-1);
}
if ((y > table.getSize().height) || (y < 0)) {
b *= (-1);
}
}
}
インスタンス249残高照会
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class QueryBalance extends JPanel {
private JTextField acctext;//
private JTextField pass;//
private JButton button1;//
private JButton button2;//
private JLabel balanceL;//
private volatile Thread lookupThread;//
public QueryBalance() {//
mainFrame();
searchEvents();
}
private void mainFrame() {
//
JLabel Lacct = new JLabel(" :");
JLabel Lpass = new JLabel(" :");
acctext = new JTextField(12);
pass = new JTextField(4);
JPanel mainPanel = new JPanel();//
mainPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
//
mainPanel.add(Lacct);
mainPanel.add(acctext);
mainPanel.add(Lpass);
mainPanel.add(pass);
// Button
button1 = new JButton(" ");
button2 = new JButton(" ");
button2.setEnabled(false);
// Button
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, -1, 5, 5));
// Button buttonPanel
buttonPanel.add(button1);
buttonPanel.add(button2);
JPanel addPanel = new JPanel();
addPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
addPanel.add(buttonPanel);// buttonPanel addPanel
JLabel balancePrefixL = new JLabel(" :");
balanceL = new JLabel(" ");
// searchPanel
JPanel searchPanel = new JPanel();
searchPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
searchPanel.add(balancePrefixL);
searchPanel.add(balanceL);
JPanel showPanel = new JPanel();
showPanel.setLayout(new GridLayout(-1, 1, 5, 5));
showPanel.add(mainPanel);
showPanel.add(addPanel);
showPanel.add(searchPanel);
setLayout(new BorderLayout());
add(showPanel, BorderLayout.NORTH);
}
private void searchEvents() {//
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchING();
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelSearch();
}
});
}
private void searchING() {//
ensureEventThread();
button1.setEnabled(false);
button2.setEnabled(true);
balanceL.setText(" ...");
//
String acct = acctext.getText();
String pin = pass.getText();
lookupMessage(acct, pin);
}
private void lookupMessage(String acct, String pin) {//
final String acctNum = acct;
final String pinNum = pin;
Runnable lookupRun = new Runnable() {
public void run() {
String bal = searchAndCheck(acctNum, pinNum);
setSafe(bal);
}
};
lookupThread = new Thread(lookupRun, "lookupThread");
lookupThread.start();
}
private String searchAndCheck(String acct, String pin) {//
try {
Thread.sleep(5000);
if (!acct.equals("220302113325") && pin.equals("198713")) {
return " !";
} else if (acct.equals("220302113325") && !pin.equals("198713")) {
return " !";
}
return "1,234.56";
} catch (InterruptedException x) {
return " ";
}
}
private void setSafe(String newBal) {//
final String newBalance = newBal;
Runnable r = new Runnable() {
public void run() {
try {
setValue(newBalance);
} catch (Exception x) {
x.printStackTrace();
}
}
};
SwingUtilities.invokeLater(r);
}
private void setValue(String newBalance) {//
ensureEventThread();
balanceL.setText(newBalance);
button2.setEnabled(false);// ,
button1.setEnabled(true);
}
private void cancelSearch() {//
ensureEventThread();
button2.setEnabled(false); // prevent additional requests
if (lookupThread != null) {
lookupThread.interrupt();
}
}
private void ensureEventThread() {
if (SwingUtilities.isEventDispatchThread()) {
return;
}
throw new RuntimeException(" ");
}
public static void main(String[] args) {
QueryBalance qb = new QueryBalance();
JFrame f = new JFrame("Balance Lookup");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.setContentPane(qb);
f.setSize(400, 150);
f.setVisible(true);
}
}
インスタンス250のスクロール文字
package Chapter17.status;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CryptoService extends JComponent {
private BufferedImage image;// BufferedImage
private Dimension imageOfSize;// Dimension
private volatile int currOffset;//
private Thread thread;//
private volatile boolean flag;
public CryptoService(String text) {
currOffset = 0;
buildImage(text);
setMinimumSize(imageOfSize);
setPreferredSize(imageOfSize);
setMaximumSize(imageOfSize);
setSize(imageOfSize);
flag = true;
Runnable r = new Runnable() {
public void run() {
try {
ScrollING();
} catch (Exception x) {
x.printStackTrace();
}
}
};
thread = new Thread(r, "ScrollText");
thread.start();
}
private void buildImage(String text) {
RenderingHints renderHints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);// RenderingHints
renderHints.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);// RenderingHints 。
BufferedImage scratchImage = new BufferedImage(1, 1,
BufferedImage.TYPE_INT_RGB);//
Graphics2D scratchG2 = scratchImage.createGraphics();// Graphics2D
scratchG2.setRenderingHints(renderHints);//
Font font = new Font("Serif", Font.BOLD | Font.ITALIC, 24);// Font
FontRenderContext frc = scratchG2.getFontRenderContext();// FontRenderContext
TextLayout tl = new TextLayout(text, font, frc);// TextLayout
Rectangle2D textBounds = tl.getBounds();// Rectangle2D
int textWidth = (int) Math.ceil(textBounds.getWidth());//
int textHeight = (int) Math.ceil(textBounds.getHeight());//
int horizontalPad = 10;// 10
int verticalPad = 6;// 6
imageOfSize = new Dimension(// Dimension
textWidth + horizontalPad, textHeight + verticalPad);
image = new BufferedImage(
// BufferedImage
imageOfSize.width, imageOfSize.height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
g2.setRenderingHints(renderHints);
int baselineOffset = (verticalPad / 2) - ((int) textBounds.getY());//
g2.setColor(Color.black);//
g2.fillRect(0, 0, imageOfSize.width, imageOfSize.height);
g2.setColor(Color.WHITE);//
tl.draw(g2, 0, baselineOffset);
scratchG2.dispose();
scratchImage.flush();
g2.dispose();
}
public void paint(Graphics g) {
// 。
g.setClip(0, 0, imageOfSize.width, imageOfSize.height);
int localOffset = currOffset; //
g.drawImage(image, -localOffset, 0, this);
g.drawImage(image, imageOfSize.width - localOffset, 0, this);
//
g.setColor(Color.red);
g.drawRect(0, 0, imageOfSize.width - 1, imageOfSize.height - 1);
}
private void ScrollING() {//
while (flag) {
try {
Thread.sleep(100);
currOffset = (currOffset + 1) % imageOfSize.width;
repaint();
} catch (InterruptedException x) {
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) {
CryptoService st = new CryptoService(" ");
JPanel p = new JPanel(new FlowLayout());
p.add(st);
JFrame f = new JFrame(" ");
f.setContentPane(p);
f.setSize(400, 100);
f.setVisible(true);
}
}
例251フローティング効果
package Chapter17;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import Chapter17.status.CryptoService;
public class FloatingEffect extends Object {
private Component comp;// Component
// X、Y
private int initX;
private int initY;
// X、Y
private int offsetX;
private int offsetY;
//
private boolean firstTime;
// Runnable
private Runnable runable;
//
private Thread thread;
//
private volatile boolean flag;
// ,
public FloatingEffect(Component comp, int initX, int initY, int offsetX,
int offsetY) {
this.comp = comp;
this.initX = initX;
this.initY = initY;
this.offsetX = offsetX;
this.offsetY = offsetY;
firstTime = true;
runable = new Runnable() {
public void run() {
newPosition();
}
};
flag = true;
Runnable r = new Runnable() {// Runnable
public void run() {
try {
floatING();
} catch (Exception x) {
// in case ANY exception slips through
x.printStackTrace();
}
}
};
thread = new Thread(r);//
thread.start();//
}
private void floatING() {//
while (flag) {
try {
Thread.sleep(200);
SwingUtilities.invokeAndWait(runable);
} catch (InterruptedException ix) {
// ignore
} catch (Exception x) {
x.printStackTrace();
}
}
}
private void newPosition() {//
if (!comp.isVisible()) {//
return;
}
Component parent = comp.getParent();//
if (parent == null) {
return;
}
Dimension parentSize = parent.getSize();
if ((parentSize == null) && (parentSize.width < 1)
&& (parentSize.height < 1)) {
return;
}
int newX = 0;
int newY = 0;
if (firstTime) {
firstTime = false;
newX = initX;
newY = initY;
} else {
Point loc = comp.getLocation();
newX = loc.x + offsetX;
newY = loc.y + offsetY;
}
newX = newX % parentSize.width;
newY = newY % parentSize.height;
if (newX < 0) {
//
newX += parentSize.width;
}
if (newY < 0) {
newY += parentSize.height;
}
comp.setLocation(newX, newY);
parent.repaint();
}
public static void main(String[] args) {//
Component[] comp = new Component[6];// Component
comp[0] = new CryptoService(" ");
comp[1] = new CryptoService(" ");
comp[2] = new ImageShow("E:\\tupian\\1.jpg", 30);
comp[3] = new ImageShow("E:\\tupian\\1.jpg", 30);
comp[4] = new ImageShow("E:\\tupian\\2.jpg", 100);
comp[5] = new ImageShow("E:\\tupian\\2.jpg", 100);
JPanel p = new JPanel();
p.setBackground(Color.white);
p.setLayout(null);
for (int i = 0; i < comp.length; i++) {
p.add(comp[i]);
int x = (int) (300 * Math.random());
int y = (int) (200 * Math.random());
int xOff = 2 - (int) (5 * Math.random());
int yOff = 2 - (int) (5 * Math.random());
new FloatingEffect(comp[i], x, y, xOff, yOff);
}
JFrame f = new JFrame(" ");
f.setContentPane(p);
f.setSize(400, 300);
f.setVisible(true);
}
}
class ImageShow extends JComponent {//
private Dimension size;//
private volatile int imgLength;//
private Thread thread;//
private Image im;//
private static String imgUrl = "";//
public ImageShow(String image, int n) {
imgUrl = image;
imgLength = 0;
size = new Dimension(n, n);
creatImage();
setMinimumSize(size);//
setPreferredSize(size);//
setMaximumSize(size);//
setSize(size);//
Runnable r = new Runnable() {
public void run() {
try {
showING();
} catch (Exception x) {
x.printStackTrace();
}
}
};
thread = new Thread(r, "ImageShow");
thread.start();
}
private void creatImage() {//
ImageIcon ic = new ImageIcon(imgUrl);
im = ic.getImage();
}
public void paint(Graphics g) {//
g.drawImage(im, imgLength, imgLength + 2, this);
}
private void showING() {//
while (true) {
try {
Thread.sleep(300); // 3
imgLength = imgLength + 1;
if (imgLength > 30) {// 30
imgLength = 0;// 0
}
repaint();//
} catch (InterruptedException x) {
Thread.currentThread().interrupt();
}
}
}
}
インスタンス252メモリの使用状況を監視する
package Chapter17;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingConstants;
//
public class Memory extends JFrame {
private JPanel panel;
private BorderLayout layout = new BorderLayout();
// JProgressBar
private JProgressBar bar_1 = new JProgressBar();
private JLabel label_1 = new JLabel();
private JLabel label_2 = new JLabel();
private void Initial() throws Exception {
panel = (JPanel) this.getContentPane();
panel.setLayout(layout);
this.setSize(new Dimension(305, 215));
this.setTitle(" ");
label_1.setFont(new java.awt.Font("Dialog", 0, 14));
label_1.setHorizontalAlignment(SwingConstants.CENTER);
label_1.setText(" ");
bar_1.setOrientation(JProgressBar.VERTICAL);
bar_1.setFont(new java.awt.Font("Dialog", 0, 14));
bar_1.setToolTipText("");
bar_1.setStringPainted(true);
label_2.setFont(new java.awt.Font("Dialog", 0, 14));
label_2.setText("");
panel.add(bar_1, BorderLayout.CENTER);
panel.add(label_1, BorderLayout.NORTH);
panel.add(label_2, BorderLayout.SOUTH);
ProgressThread pt = new ProgressThread(this.bar_1, this.label_2);
pt.start();
this.setVisible(true);
}
public static void main(String[] args) {
try {
new Memory().Initial();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ProgressThread extends Thread {
JProgressBar jpb;
JLabel jl;
public ProgressThread(JProgressBar jpb, JLabel jl) {
this.jpb = jpb;
this.jl = jl;
}
public void run() {
int min = 0;
int max = 100;
int free = 0;
int totle = 0;
int status = 0;
jpb.setMinimum(min);
jpb.setMaximum(max);
jpb.setValue(status);
while (true) {
totle = (int) (Runtime.getRuntime().totalMemory() / 1024);
free = (int) (Runtime.getRuntime().freeMemory() / 1024);
jl.setText(" "
+ (int) (Runtime.getRuntime().freeMemory() / 1024) + "K"
+ " :"
+ (int) (Runtime.getRuntime().totalMemory() / 1024) + "K");
status = (int) (free * 100 / totle);
jpb.setValue(status);
jpb.setString(" :" + status + "%");
try {
this.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
例253きらきら光る星空
package Chapter17.example;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
public class Universe extends java.applet.Applet implements Runnable {
int Width, Height;//
Thread thread = null;//
boolean suspend = false;//
Image im;//
Graphics graphics;// Graphics
double rot, dx, ddx;// double
int speed, stars, type;// int
double defddx, max;// double
Star pol[]; //
public void init() {// Applet
rot = 0;
dx = 0;
ddx = 0;
Width = 300;
Height = 300;
String theSpeed = "25";
Show("speed", theSpeed);
speed = (theSpeed == null) ? 50 : Integer.valueOf(theSpeed).intValue();
String theStars = "250";
Show("stars", theStars);
stars = (theStars == null) ? 30 : Integer.valueOf(theStars).intValue();
try {
im = createImage(Width, Height);
graphics = im.getGraphics();
} catch (Exception e) {
graphics = null;
}
pol = new Star[stars];
for (int i = 0; i < stars; i++)
pol[i] = new Star(Width, Height, 150, type);
System.out.println(Width + "," + Height);
}
public void paint(Graphics g) {//
if (graphics != null) {
paintStart(graphics);
g.drawImage(im, 0, 0, this);
} else {
paintStart(g);
}
}
public void paintStart(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, Width, Height);
for (int i = 0; i < stars; i++)
pol[i].DrawSelf(g, rot);
}
public void start() {// Applet
if (thread == null) {
thread = new Thread(this);
thread.start();//
}
}
public void stop() {// Applet
if (thread != null) {
thread.stop();
thread = null;
}
}
public void run() {//
while (thread != null) {
rot += dx;
dx += ddx;
if (dx > max)
ddx = -defddx;
if (dx < -max)
ddx = defddx;
try {
Thread.sleep(speed);
} catch (InterruptedException e) {
}
repaint();
}
}
public void update(Graphics g) {//
paint(g);
}
public void Show(String theString, String theValue) {
if (theValue == null) {
System.out.println(theString + " : null");
} else {
System.out.println(theString + " : " + theValue);
}
}
}
class Star {//
int H, V;
int x, y, z;
int type;
Star(int width, int height, int depth, int type) {//
this.type = type;
H = width / 2;
V = height / 2;
x = (int) (Math.random() * width) - H;
y = (int) (Math.random() * height) - V;
if ((x == 0) && (y == 0))
x = 10;
z = (int) (Math.random() * depth);
}
public void DrawSelf(Graphics g, double rot) {//
double X, Y;
int h, v, hh, vv;
int d;
z -= 2;
if (z < -63)
z = 100;
hh = (x * 64) / (64 + z);
vv = (y * 64) / (64 + z);
X = (hh * Math.cos(rot)) - (vv * Math.sin(rot));
Y = (hh * Math.sin(rot)) + (vv * Math.cos(rot));
h = (int) X + H;
v = (int) Y + V;
if ((h < 0) || (h > (2 * H)))
z = 100;
if ((v < 0) || (v > (2 * H)))
z = 100;
setColor(g);
if (type == 0) {
d = (100 - z) / 50;
if (d == 0)
d = 1;
g.fillRect(h, v, d, d);
} else {
d = (100 - z) / 20;
g.drawLine(h - d, v, h + d, v);
g.drawLine(h, v - d, h, v + d);
if (z < 50) {
d /= 2;
g.drawLine(h - d, v - d, h + d, v + d);
g.drawLine(h + d, v - d, h - d, v + d);
}
}
}
public void setColor(Graphics g) {//
if (z > 50) {
g.setColor(Color.gray);
} else if (z > 25) {
g.setColor(Color.lightGray);
} else {
g.setColor(Color.white);
}
}
}
例254銀行とスーパー業務のシミュレーション
package Chapter17.bank;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class SimulationSite extends Frame implements ActionListener {//
//
protected static final int num_agents=10;
protected static final int num_initial_agents=6;
protected static final int max_customer_delay=9000;
protected static final int max_teller_break=1000;
protected static final int max_no_customers=2000;
// Button
private Button open = new Button(" ");
private Button close = new Button(" ");
private Button add = new Button(" ");
private Button del = new Button(" ");
private Bank bank = new Bank();
private Finance supermarket = new Finance("");
//
private class WindowCloser extends WindowAdapter{
public void windowClosing(WindowEvent e){
bank.stop();
supermarket.stop();
System.exit(0);
}
}
public SimulationSite(){// ,
super("SimulationSite");
Panel buttons = new Panel();
buttons.setLayout(new FlowLayout());
buttons.add(open);
open.addActionListener(this);
buttons.add(close);
close.addActionListener(this);
buttons.add(add);
add.addActionListener(this);
buttons.add(del);
del.addActionListener(this);
this.addWindowListener(new WindowCloser());
this.setLayout(new BorderLayout());
add("West",bank);
add("East",supermarket);
add("South",buttons);
validate();
pack();
show();
bank.start();
supermarket.start();
}
public void actionPerformed(ActionEvent e) {//
// TODO Auto-generated method stub
if(e.getSource()==open){
bank.openDoor();
supermarket.openDoor();
}else if(e.getSource()==close){
bank.closeDoor();
supermarket.closeDoor();
}else if(e.getSource()==add){
bank.addAgent();
supermarket.addAgent();
}else if(e.getSource()==del){
bank.retireAgent();
supermarket.retireAgent();
}
}
public static void main(String[] args){//
SimulationSite sl = new SimulationSite();
}
}
class Finance extends Panel implements Runnable {
protected Penson[] person = new Penson[SimulationSite.num_agents];
protected Label[] labelAgent = new Label[SimulationSite.num_agents];
protected Label labelQueue = new Label(" :0");
protected Label labelServed = new Label("Customers servers:0");
protected Label labelWait = new Label("Customers wait:0");
protected int numAgents = SimulationSite.num_initial_agents;
protected int numCustomer = 0;//
protected long totalWait = 0L;//
private Thread thread = null;
private boolean doorIsOpen = false;
public Finance(String title) {
super();
setup(title);
}
public void updateDisplay() {
}
public void generateCustomer() {
}
public Customer requestCustomerFor(int id) {
return null;
}
public void checkoutCustomer(int handled, long waitTime) {// ,
numCustomer++;
totalWait += waitTime;
}
public void addAgent() {//
if (numAgents < SimulationSite.num_agents) {
person[numAgents] = new Penson(this, numAgents);
person[numAgents].start();
numAgents++;
}
}
public void retireAgent() {//
if (numAgents > 1) {
person[numAgents - 1].setRunING();
numAgents--;
}
}
public void start() {
if (thread == null) {
thread = new Thread(this);
doorIsOpen = true;
thread.start();//
for (int i = 0; i < numAgents; i++) {
person[i].start();// Person
}
}
}
public void stop() {
doorIsOpen = false;
thread = null;
for (int i = 0; i < numAgents; i++) {
person[i].setRunING();
}
}
public void openDoor() {//
doorIsOpen = true;
}
public void closeDoor() {//
doorIsOpen = false;
}
public void run() {// Runnable run
while (thread == Thread.currentThread()) {
try {
thread.sleep((int) Math.random()
* SimulationSite.max_no_customers);
if (doorIsOpen) {
generateCustomer();
updateDisplay();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void setup(String title) {//
Panel agentPanel = new Panel();
agentPanel.setLayout(new GridLayout(SimulationSite.num_agents + 3, 1));
for (int i = 0; i < SimulationSite.num_agents; i++) {
labelAgent[i] = new Label("Penson" + i + ":served 0");
agentPanel.add(labelAgent[i]);
person[i] = new Penson(this, i);
}
for (int i = numAgents; i < SimulationSite.num_agents; i++) {
labelAgent[i].setText("Penson" + i + ":inactive");
}
agentPanel.add(labelQueue);
agentPanel.add(labelServed);
agentPanel.add(labelWait);
setLayout(new BorderLayout());
add("Center", agentPanel);
add("North", new Label(title));
}
}
class Penson extends Thread {// Thread Penson
private boolean running = false;//
private Finance bn = null;
private int id = -1;// id
private int numCustomers = 0;//
public Penson(Finance _bn, int _id) {
this.bn = _bn;
this.id = _id;
}
public void start() {
running = true;
super.start();//
}
public void setRunING() {//
running = false;
}
public int getNum() {//
return numCustomers;
}
private void releaseCustomer(Customer customer) {//
numCustomers++;
bn.checkoutCustomer(numCustomers, customer.getWaitTime(new Date()));
}
public void run() {// Thread run
while (running) {
try {
sleep((int) (Math.random() * SimulationSite.max_teller_break) + 1000);//
Customer customer = bn.requestCustomerFor(id);
if (customer != null) {
sleep(customer.getDelayTime());
releaseCustomer(customer);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Bank extends Finance implements Runnable {
private ObjectQueue queue = null;
public Bank() {
super(" ");//
queue = new ObjectQueue();// ObjectQueue
}
public void updateDisplay() {//
labelServed.setText(" :" + numCustomer);//
if (numCustomer != 0) {
labelWait.setText(" :" + (totalWait / numCustomer));
for (int i = 0; i < numAgents; i++) {
labelAgent[i].setText(" :" + i + ": " + person[i].getNum());
}
for (int i = numAgents; i < SimulationSite.num_agents; i++) {
labelAgent[i].setText(" :" + i + ": ");
labelQueue.setText(" :" + queue.getSize());
}
}
}
public void generateCustomer() {// ,
queue.insert(new Customer());
}
public Customer requestCustomerFor(int id) {//
return queue.requestCustomer();
}
}
//class SimulationSite extends Frame implements ActionListener {//
// //
// protected static final int num_agents = 10;
// protected static final int num_initial_agents = 6;
// protected static final int max_customer_delay = 9000;
// protected static final int max_teller_break = 1000;
// protected static final int max_no_customers = 2000;
// // Button
// private Button open = new Button(" ");
// private Button close = new Button(" ");
// private Button add = new Button(" ");
// private Button del = new Button(" ");
// private Bank bank = new Bank();
// private Hypermarket supermarket = new Hypermarket();
// //
// private class WindowCloser extends WindowAdapter {
// public void windowClosing(WindowEvent e) {
// bank.stop();
// supermarket.stop();
// System.exit(0);
// }
// }
// public SimulationSite() {// ,
// super("SimulationSite");
// Panel buttons = new Panel();
// buttons.setLayout(new FlowLayout());
// buttons.add(open);
// open.addActionListener(this);
// buttons.add(close);
// close.addActionListener(this);
// buttons.add(add);
// add.addActionListener(this);
// buttons.add(del);
// del.addActionListener(this);
// this.addWindowListener(new WindowCloser());
// this.setLayout(new BorderLayout());
// add("West", bank);
// add("East", supermarket);
// add("South", buttons);
// validate();
// pack();
// show();
// bank.start();
// supermarket.start();
// }
// public void actionPerformed(ActionEvent e) {//
// // TODO Auto-generated method stub
// if (e.getSource() == open) {
// bank.openDoor();
// supermarket.openDoor();
// } else if (e.getSource() == close) {
// bank.closeDoor();
// supermarket.closeDoor();
// } else if (e.getSource() == add) {
// bank.addAgent();
// supermarket.addAgent();
// } else if (e.getSource() == del) {
// bank.retireAgent();
// supermarket.retireAgent();
// }
// }
// public static void main(String[] args) {//
// SimulationSite sl = new SimulationSite();
// }
//}
class ObjectQueue {//
private List customers = new ArrayList();
private synchronized Object performAction(String cmd, Object obj) {//
if (cmd.equals("insert")) {//
if (customers.isEmpty())
customers.add(obj);
notify();
return null;
} else if (cmd.equals("size")) {//
return new Integer(customers.size());
} else if (cmd.equals("retrieve")) {
while (customers.size() == 0) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Customer c = (Customer) customers.get(0);
customers.remove(0);
return c;
}
return null;
}
public void insert(Customer c) {//
performAction("insert", c);
}
public int getSize() {//
return (((Integer) performAction("size", null)).intValue());
}
public Customer requestCustomer() {//
return (Customer) performAction("retrieve", null);
}
}
class Customer {//
private Date date;//
public Customer() {// , date
date = new Date();
}
public int getDelayTime() {//
return (int) (Math.random() * SimulationSite.max_customer_delay);
}
public long getWaitTime(Date now) {//
return now.getTime() - date.getTime();
}
}