//DeadClass4.java
//线程优先级
//2009-11-22
//<applet code=DeadClass4 width=200 height=100>
//</applet>
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DeadClass4 extends JApplet
{
int count1=0;
int count2=0;
JTextField txt1=new JTextField(5);
JTextField txt2=new JTextField(5);
JTextField txt3=new JTextField(14);
JButton increase=new JButton("Increase");
JButton decrease=new JButton("Decrease");
class ThreadClass extends Thread
{
int count;
boolean flag;
public void run(){
while (true)
{
try
{
sleep(20);
}
catch (InterruptedException e)
{
}
if (flag)
{
txt1.setText(Integer.toString(count1++));
}
else
txt2.setText(Integer.toString(count2--));
txt3.setText("count1+count2= "+Integer.toString(count1+count2));
}
}
}
ThreadClass increaseT;
ThreadClass decreaseT;
class IncreaseButtonLis implements ActionListener
{
public void actionPerformed(ActionEvent e){
if (increaseT==null)
{
increaseT=new ThreadClass();
increaseT.flag=true;
increaseT.setPriority(Thread.MAX_PRIORITY);//设置高优先级。
increaseT.start();
}
}
}
class DecreaseButtonLis implements ActionListener
{
public void actionPerformed(ActionEvent e){
if (decreaseT==null)
{
decreaseT=new ThreadClass();
decreaseT.flag=false;
decreaseT.setPriority(Thread.MIN_PRIORITY);//设置低优先级
decreaseT.start();
}
}
}
public void init(){
Container cp=getContentPane();
cp.setLayout(new FlowLayout());
cp.add(txt1);
cp.add(txt2);
cp.add(txt3);
cp.add(increase);
cp.add(decrease);
increase.addActionListener(new IncreaseButtonLis());
decrease.addActionListener(new DecreaseButtonLis());
}
}