就是启动另一个线程,如此交替运行,实现侦听。注意这两个线程功能相同,所以可以是同一个类的不同对象,这个类如下(参考,大家可以自己编写):
class MyThread extends Thread{ String name;
StringBuffer sendString; StringBuffer recvString;
MyThread(String name, StringBuffer sendString, StringBuffer recvString) { this.name = name;
this.sendString = sendString; this.recvString = recvString; } @Override
publicvoid run() {
//循环100次,每次循环都sleep一段随机事件,然后收发消息 for(int i = 0; i < 100; i++) {
int time = (int)(Math.random() * 100); try { sleep(time); }
catch(Exception e) {
e.printStackTrace(); }
sendMsg(); recvMsg(); } } //发送消息
publicvoid sendMsg() { synchronized(sendString) { while(sendString.length() > 0) { try {
sendString.wait(); } catch(Exception e) {
e.printStackTrace(); } }
double content = Math.random(); sendString.append(name + content);
System.out.println(name + \ + content); sendString.notify(); } } //接收消息
publicvoid recvMsg() { synchronized(recvString) { while(recvString.length() == 0) { try {
recvString.wait(); } catch(Exception e) {
e.printStackTrace(); } }
System.out.println(name + \ + recvString); recvString.delete(0, recvString.length()); recvString.notify(); } } }
请详细分析看懂以上代码,然后自己修改适合自己的类,最后编写测试类,实现题意功能,运行结果见下:
我选择了模拟银行账户类,代码如下:
package zi;
class MbankCompex { //模拟银行账户类
class UserGetMoney extends Thread{ //模拟用户取款的线程类
publicvoid run(){ for(int i=1;i<=4;i++){ MbankCompex.take(100); } } }
publicclass Ex8_5 { //调用线程的主类
publicstaticvoid main(String[] args) { UserGetMoney u1 = new UserGetMoney(); UserGetMoney u2 = new UserGetMoney(); u1.start(); u2.start(); } }
privatestaticintsum = 2000;
publicsynchronizedstaticvoid take(int k){ //限定take为同步方法 int temp = sum; temp -= k; try {
Thread.sleep((int)(100*Math.random()));} catch (InterruptedException e) {} sum = temp;
System.out.println(Thread.currentThread()+\+sum); } }
运行结果截图如下:
6【选做】,编写一个应用程序,除了主线程外,还有两个线程:first和second。first负责模拟一个红色的按钮从坐标(10,60)运动到(100,60);second负责模拟一个绿色的按钮从坐标(100,60)运动到(200,60),输出模拟过程。(要结合第9章的画图知识)
依题意,代码如下:
package zi;
import javax.swing.*; import java.awt.*;
publicclassEx8_6extends JFrame implements Runnable{ Thread first=new Thread(this,\); Thread Second=new Thread(this,\); JButton green=new JButton(); JButton red=new JButton();
JLabel lgreen=new JLabel(\); JLabel lred=new JLabel(\); intx=10,y=60,x1=100; Ex8_6(){
setLayout(null);
green.setBackground(Color.green); green.setBounds(100,60,30,20); red.setBackground(Color.red); red.setBounds(10,60,30,20); lred.setBounds(10,50,50,10); lgreen.setBounds(100,80,50,10); add(green);add(red); add(lgreen);add(lred); setSize(300,250); setVisible(true); first.start(); }
publicvoid run(){
String cr=Thread.currentThread().getName(); if(cr.equals(\)){ while(x<100){ try{ x+=10;
red.setLocation(x,y); lred.setLocation(x,y-10); lred.setText(x+\); Thread.sleep(200);
}catch(Exception e){} }
Second.start(); } else{
while(x1<200){ try{ x1+=10;
green.setLocation(x1,y); lgreen.setLocation(x1,y+20); lgreen.setText(x1+\); Thread.sleep(200); }catch(Exception e){} } } }
publicstaticvoid main(String args[]){ new Ex8_6(); } }
其运行结果如下所示: