javafx开始暂停

package com.company;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;


public class Main extends Application {
    public static int zt = 0;

    public static void main(String[] args) {
        Application.launch(Main.class, args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        Worker worker = new Worker();
        worker.setDaemon(true);
        worker.start();


        Button button = new Button("开始移动");
        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                zt++;
                button.setText("正在移动...");
                if (zt % 2 == 1) {
                    System.out.println("开始运行了");
                    synchronized (worker) {
                        worker.setPaused(false);
                        worker.notify();
                    }
                } else {
                    System.out.println("暂停了");
                    button.setText("开始移动");
                    worker.setPaused(true);
                }


            }
        });

        AnchorPane a5 = new AnchorPane();
        a5.getChildren().add(button);


        Scene scene = new Scene(a5);
        primaryStage.setScene(scene);
        primaryStage.setWidth(800);
        primaryStage.setHeight(800);
        primaryStage.setTitle("移动文件");
//        primaryStage.getIcons().add(new Image("http://www.haotuo.net.cn/Resources/cq/qunlogo.png"));
        primaryStage.show();


    }


}

class Worker extends Thread {
    private volatile boolean isPaused = true;

    public void setPaused(boolean paused) {
        isPaused = paused;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                while (isPaused) {
                    try {

                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            // 执行工作任务
            System.out.println(123);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值