⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 threadexp11.java

📁 java关于多线程的课堂练习
💻 JAVA
字号:
/**
 * @(#)ThreadExp11.java
 *
 *
 * @author 
 * @version 1.00 2007/11/29
 */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class MyFrame extends JFrame implements Runnable,ActionListener {
 售票员 王小姐;
 Thread  张平,李明;
 static JTextArea  text;
 JButton  startBuy=new JButton("开始买票");
 MyFrame() {
 王小姐=new 售票员();
 张平=new Thread(this);
 李明=new Thread(this);
 text=new JTextArea(10,30);
 startBuy.addActionListener(this);
 add(text,BorderLayout.CENTER);
 add(startBuy,BorderLayout.NORTH);
 setVisible(true);
 setSize(360,300);
 validate();
 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
 public void actionPerformed(ActionEvent e) {
 	try {
 	张平.start();
 	李明.start();
 	}
 	catch (Exception exp) {
 		System.out.println("start thread error!");
 	}
 }
 public void run() {
 	if (Thread.currentThread()==张平) {
 	 王小姐.售票规则(20);
 	}
 	else if (Thread.currentThread()==李明) {
 	 王小姐.售票规则(5);
 	}
 }
}
class 售票员 {
 int 五元钱的张数=2,十元钱的张数=0,二十元钱的张数=0;
 public synchronized void 售票规则(int money) {
  if (money==5) {
   五元钱的张数++;
   MyFrame.text.append("\n给您入场券 您的钱正好!");
  }
  else if (money==20) {
   while (五元钱的张数<3) {
   	try {
   	 wait();
   	}
   	catch (InterruptedException e) { }
   }
   五元钱的张数-=3;
   二十元钱的张数++;
   MyFrame.text.append("\n给您入场券 您给我20,找您15元");
  }
  notifyAll();
 }
}

public class ThreadExp11 {
        
    /**
     * Creates a new instance of <code>ThreadExp11</code>.
     */
    public ThreadExp11() {
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        new MyFrame();
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -