簡體   English   中英

我需要將變量傳遞給線程

[英]I need to pass an variable into a thread

Thread thread1;
thread1 = new Thread() {
    public void run() {
        try {
            Thread.sleep(1700);
        } catch (InterruptedException ex) {
            Logger.getLogger(TestThread.class.getName()).log(Level.SEVERE, null, ex);
        }
       System.out.println("testing");
    }
};
Thread thread2;
thread2 = new Thread() {
    public void run() {
        try {
            // ... your code here
            Thread.sleep(1000);
            System.out.println("testing");
        } catch (InterruptedException ex) {
            Logger.getLogger(TestThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
};
thread1.start();
thread2.start();
System.out.println("testing");

這是我程序的簡化版本,突出了我需要在睡眠時傳遞的問題,但是環顧四周后,似乎無法傳遞給我,我只能找到有關傳遞給可運行的信息。

嘗試在下課下跑步,您有任何問題嗎

public class TestThread {

    volatile static int time = 1700;

    public static void main(String[] args) {


        Thread thread1 = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread1 Sleeped for : " + time + " millis");
            }
        };
        thread1.start();

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread2 Sleeped for : " + time + " millis");
            }
        };
        thread2.start();
    }

}

您可以嘗試創建一個耗時的線程工廠並執行您的自定義代碼:

interface CodeExecutor {
    void execute();
}

static class ThreadFactory {
    public static Thread newThread(int sleepTime, CodeExecutor customCode) {
        return new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    customCode.execute();
                    Thread.sleep(sleepTime);
                    System.out.println("testing");
                } catch (InterruptedException ex) {
            Logger.getLogger(TestThread.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
}

public static void main(String[] args) {
    Thread thread1 = ThreadFactory.newThread(100, new CodeExecutor() {
        @Override
        public void execute() {
            // here goes your custom code
        }
    });

    thread1.start();
    // create other threads
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM