(1)一个线程进行阶乘和的运算(1!+2!+3!+……+12!),每次阶乘计算时间随机间隔0.5-1秒;
(2)另一个线程每隔1秒时间读取上个线程的运算结果和计算进程,并在图形界面中实时显示结果。
图形化界面类
package basetest;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.Font;
public class Calc {
private JFrame frame;
JTextField textField;
JTextArea textArea;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Calc window = new Calc();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Calc() {
initialize();
}
private void initialize() {
frame = new JFrame("多线程小应用");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textArea = new JTextArea();
textArea.setBounds(114, 42, 264, 59);
frame.getContentPane().add(textArea);
textField = new JTextField();
textField.setBounds(114, 132, 264, 21);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton button = new JButton(" \u542F\u52A8\u7EBF\u7A0B");
button.setBounds(195, 190, 97, 23);
frame.getContentPane().add(button);
JLabel label = new JLabel("\u8BA1\u7B97\u8FDB\u7A0B");
label.setFont(new Font("宋体", Font.PLAIN, 17));
label.setBounds(37, 62, 67, 21);
frame.getContentPane().add(label);
JLabel label_1 = new JLabel("\u8BA1\u7B97\u7ED3\u679C");
label_1.setBounds(37, 135, 58, 15);
frame.getContentPane().add(label_1);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
deal();
}
});
}
private void deal() {
Compulate c = new Compulate();
Thread t = new Thread(c);
t.start();
Read r = new Read(this);
r.start();
}
}
计算线程类
package basetest;
import java.util.Random;
public class Compulate implements Runnable{
long sum = 0;
static int i = 0;
static String stringSum = "";
static String stringResult = "";
long method(int n) {
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
public void run() {
while(i<12) {
i++;
sum += method(i);
System.out.println(sum);
stringResult = sum + "";
if(i!=1) {
stringSum += "+" + i + "!";
}
else {
stringSum = i + "!";
}
Random r = new Random();
try {
Thread.sleep((r.nextInt(500))+500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
显示结果线程类
package basetest;
import java.util.Random;
public class Read extends Thread{
Calc calc;
Read(Calc calc){
this.calc = calc;
}
public void run() {
while(true) {
calc.textArea.setText(Compulate.stringSum);
calc.textField.setText(Compulate.stringResult);
Random r = new Random();
try {
sleep((r.nextInt(500))+500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}