运用多线程和GUI制作一个如下图的抽奖界面,随着点击按钮,开始随机选取手机号作为中奖用户。要用到两个线程,一个主线程,我们在创建一个子线程,使用wait()和notify()方法休眠与唤醒来实现抽奖时的暂停与继续。
运行界面:
点击开始,进行随机选号:
代码展示:
package multithreading;import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.Random;public class Lottery extends JFrame {private JLabel l,l2;private JButton b;String []number={"18109780525","18290450569","13145678954","13596352525","12378984911", "12768738812", "18395678910", "17842365714","15699569782","17699818998","18044659078","18799870521"};public Lottery(){this.setTitle("手机号抽奖");this.setBounds(550,100,500,300);this.getContentPane().setBackground(Color.LIGHT_GRAY);l=new JLabel("随机摇号");l2 = new JLabel("中国体育彩票");l.setHorizontalAlignment(SwingConstants.CENTER);l2.setHorizontalAlignment(SwingConstants.CENTER);l.setForeground(Color.RED);l.setFont(new Font("宋体",Font.PLAIN,62));l2.setFont(new Font("黑体",Font.PLAIN,22));b=new JButton("开始");this.add(l,BorderLayout.CENTER);this.add(l2,BorderLayout.NORTH);this.add(b,BorderLayout.SOUTH);this.setVisible(true);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);myThread t=new myThread();b.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {String str = b.getText();if (str.equals("暂停")) {t.changeflag1();b.setText("继续");} else {b.setText("暂停");t.changeflag2();}}});t.start();}class myThread extends Thread{boolean flag=true;public synchronized void changeflag1(){flag=true;}public synchronized void changeflag2(){flag=false;notify();}public void run(){do {synchronized (this) {while (flag) {try {wait();} catch (InterruptedException e) {e.printStackTrace();}}}int i = new Random().nextInt(number.length);String name = number[i];l.setText(name);String substring = name.substring(name.length() - 4);l2.setText("恭喜尾号为:"+substring+"的用户,获得年度最佳鼓励奖。");} while (true);}}public static void main(String[] args) {new Lottery();}}
如果觉得《java多线程和GUI实现抽奖界面》对你有帮助,请点赞、收藏,并留下你的观点哦!