就是在 run(){
print...
while(!stop){
//这里
}
print.close()
}
然后不用这个输入输出的时候,线程就可以挂起sleep,用的时候在notify唤醒一下,
直到你不用的时候,再把那个stop标识设置为true,他就跳出了这个循环,这时候再将print关闭
import java.applet.*import javax.swing.*
import java.awt.*
import java.awt.event.*
import java.util.*
public class UseRunnable extends Applet implements ActionListener{
JButton b1,b2,b3,b11,b22,b33
JTextField t1,t2,t3
Random rand=new Random(47)
int[] a={65,97} Thread f1,f2,f3
boolean a1,a2,a3
public void init( ){
setLayout(new FlowLayout( ))
b1=new JButton("激活1") b11=new JButton("挂起1") t1=new JTextField(5)t1.setEditable(false)
add(b1) add(b11) add(t1)
b2=new JButton("激活2") b22=new JButton("挂起2") t2=new JTextField(5)t2.setEditable(false)
add(b2)add(b22)add(t2)
b3=new JButton("激活3") b33=new JButton("挂起3") t3=new JTextField(5)t3.setEditable(false)
add(b3)add(b33)add(t3)
setBackground(Color.LIGHT_GRAY)
resize(250,110)
b1.addActionListener(this)b11.addActionListener(this)
b2.addActionListener(this)b22.addActionListener(this)
b3.addActionListener(this)b33.addActionListener(this)
}
class A implements Runnable{
public void run( ){
while(true){
while(a1){getstop( )}
t1.setText(gett( ))
try{Thread.sleep((int)(Math.random()*500))}catch(Exception e){}
}
}
}
class B implements Runnable{
public void run( ){
while(true){
while(a2){getstop( )}
t2.setText(gett( ))
try{Thread.sleep((int)(Math.random( )*500))}catch(Exception e){}
}
}
}
class C implements Runnable{
public void run( ){
while(true){
while(a3){getstop( )}
t3.setText(gett( ))
try{Thread.sleep((int)(Math.random( )*500))}catch(Exception e){}
}
}
}
public String gett( ){
int i1=a[rand.nextInt(2)]
return String.valueOf((char)(rand.nextInt(26)+i1))
}
public void start( ){
f1=new Thread(new A( ))
f2=new Thread(new B( ))
f3=new Thread(new C( ))
f1.start( )f2.start( )f3.start( )
}
public synchronized void getstop( ){try{wait( )}catch(Exception e1){}}
public synchronized void getstart( ){notifyAll( )}
public void actionPerformed(ActionEvent e){
if(e.getSource( )==b1){a1=falsegetstart( )}
if(e.getSource( )==b11){a1=true}
if(e.getSource( )==b2){a2=falsegetstart( )}
if(e.getSource( )==b22){a2=true}
if(e.getSource( )==b3){a3=falsegetstart( )}
if(e.getSource( )==b33){a3=true}
}
}
要利用循环啊!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)