public class ServerClient {
static class Client {
final int time;
final int id;
Client(int id) {
this.time = (new Random().nextInt(10) + 1) * 1000 * 1;
this.id = id;
}
}
static class Request {
final ArrayList<Client> list = new ArrayList<Client>();
int i = 0;
Request(int n) {
for (int i = 0; i < n; i++) {
list.add(new Client(i + 1));
}
}
public synchronized Client getRequest() {
if (i >= list.size()) {
return null;
}
return list.get(i++);
}
}
static class Server extends Thread {
final int id;
final Request request;
Server(int id, Request request) {
this.id = id;
this.request = request;
}
private void response(Client c) throws InterruptedException {
System.out.println(id + "号服务器正在被用户" + c.id + "访问");
Thread.sleep(c.time);
}
@Override
public void run() {
System.out.println(id + "号服务器准备就绪...");
while (true) {
Client c = request.getRequest();
if (c == null) {
break;
}
try {
response(c);
} catch (InterruptedException e) {
System.out.println("访问异常," + id + "号服务器将在一段时间内重新进行响应");
try {
Thread.sleep(c.time);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
run();
}
}
System.out.println(id+"号服务器访问结束!!!");
}
}
static class Window extends JFrame{
public Window(){
setTitle("服务器并行访问控制");
setBounds(200, 200, 380, 170);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Admin admin = new Admin();
admin.start();
JButton jButton = new JButton("开始");
Font f=new Font("宋体",Font.BOLD,40);
jButton.setFont(f);
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String Btn = jButton.getText();
if(Btn.equals("暂停"))
{
try {
admin.toSuspend();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
jButton.setText("开始");
}else{
admin.toResume();
jButton.setText("暂停");
}
}
});
getContentPane().add(jButton, BorderLayout.CENTER);
setVisible(true);
}
class Admin extends Thread{
Request request = new Request(10);
Server s1=new Server(1,request);
Thread server1=new Thread(s1);
Server s2=new Server(2,request);
Thread server2=new Thread(s2);
Server s3=new Server(3,request);
Thread server3=new Thread(new Server(3,request));
private boolean suspend = true;
public synchronized void toSuspend() throws InterruptedException{
suspend = true;
System.out.println("线程暂停...");
}
public synchronized void toResume(){
notify();//当前等待的线程继续执行
suspend = false;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
synchronized (this) {
while(suspend){
try {
wait();//让线程进入等待状态
server1.start();
server2.start();
server3.start();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
}
public static void main(String[] args) throws Exception {
new Window();
}
}
04-16
1008