Comment accéder au thread / runnable en cours d’exécution?

J’ai un thread en cours d’exécution mais de l’extérieur je ne peux pas contourner une valeur pour arrêter ce thread. Comment puis-je envoyer une valeur false / true dans Mytest() ou appeler des méthodes publiques de thread en cours d’exécution? Quand j’appuie sur le bouton1? ex: thread.interrupt(); runnable.stop(); ou runnable.start();

 // Main public class Main extends JFrame { public static Runnable runnable; public static Thread thread; private JButton b1 = new JButton("Start/Stop"); public void init() { //Execute a job on the event-dispatching thread: try { javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { createGUI(); } }); } catch (Exception e) { System.err.println("createGUI didn't successfully complete"); } } public void createGUI() { Container cp = getContentPane(); b1.addActionListener(new button1()); cp.add(b1); runnable = new Mytest(); thread = new Thread(runnable); thread.start(); } } // Button 1 - [problem to go inside a running thread] public class button1 implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("button pressed - need to access "); //thread.interrupt(); runnable.stop(); //or runnable.start(); } } // Running - Thread public class Mytest implements Runnable { public static boolean onoff = false; public static boolean status = false; public void run() { while(true) { if (onoff) { return; } else { if (status==false) System.out.println("running"); } } } public static void stop() { status = true; onoff=true; } public static void start() { status = false; onoff = false; } } 

Suivi (relecture):

 Step 1: /* Main - boot/startup */ public class Main extends JFrame { public static Mytest runnable; // wrong: public static Runnable runnable; public static Thread thread; private JButton b1 = new JButton("Start"); private JButton b2 = new JButton("Stop"); public void init() { // Execute a job on the event-dispatching thread: // In case Freezed for heavy lifting try { javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { createGUI(); } }); } catch (Exception e) { System.err.println("createGUI didn't successfully complete"); } } public void createGUI() { Container cp = getContentPane(); b1.addActionListener(new button1()); cp.add(b1); runnable = new Mytest(); thread = new Thread(runnable); try { thread.sleep(100); // value is milliseconds thread.start(); } catch (InterruptedException e) { } } public static void main(Ssortingng[] args) { run(new Main(), 500, 500); } public static void run(JFrame frame, int width, int height) { ... frame.setVisible(true); } } /* To start */ public class button1 implements ActionListener { public void actionPerformed(ActionEvent e) { runnable.start(); } } /* To stop */ public class button2 implements ActionListener { public void actionPerformed(ActionEvent e) { runnable.stop(); } } Step 2: /* Thread deals */ public class Mytest implements Runnable { private static volatile boolean running = true; public void run() { while(running) { // do stuff } } public void start() { running = true; } public void stop() { running = false;} } 

si vous le définissez par classe plutôt que comme Runnable vous pouvez appeler les méthodes d’instance.

 public static Mytest runnable; 

Notez également qu’en raison de la mémoire associée à plusieurs cœurs, vous devez avertir le processeur que l’état peut être modifié sur un autre processeur et qu’il doit surveiller ce changement. Cela semble compliqué, mais ajoutez simplement le mot clé ‘volatile’ aux drapeaux booléens

 public class Mytest implements Runnable { private static volatile boolean running = true; public void run() { while(running) { // do stuff } } public void stop() { running = false;} } 

Démarrez le Runnable comme dans votre code initial, puis arrêtez-le en utilisant runnable.stop()

Vous devriez toujours utiliser la méthode d’interruption pour arrêter un thread. C’est un moyen sûr et adéquat d’effectuer une opération d’arrêt sur un thread.

 Thread tThread = new Thread(new Runnable() { public void run() { while (!Thread.currentThread().isInterrupted()) { try{ Thread.sleep(10); ... do you stuff... }catch(InterruptedException ex){ break; } } } }); tThread.start(); 

Et lorsque vous souhaitez arrêter votre thread, appelez simplement la méthode d’interruption:

 tThread.interrupt(); 
public void run() { while(!isInterrupted()) { if (onoff) { return; } else { if (status==false) System.out.println("running"); } } }
public void run() { while(!isInterrupted()) { if (onoff) { return; } else { if (status==false) System.out.println("running"); } } } 

Ensuite, utilisez Thread.interrupt () pour indiquer une interruption du thread.

Remarque: N’utilisez Thread.stop () sous aucun prétexte ! C’est obsolète !
Pour plus de détails, vous pouvez consulter le document JDK et << Java Concurrency in Practice >>.

dans votre méthode de course …

ne fais pas tout (vrai) ..

utilisez un booléen … comme … while (threadIsRunning)

et ce booléen vous pouvez définir vrai / faux ….

En dehors du fait que ce fil est un test de chauffage pour votre CPU;)

Vous pouvez appeler les méthodes start / stop avec

  MyThread.start(); MyThread.stop(); 

Vous les avez définies en tant que méthodes static . Les lignes de code ci-dessus indiquent comment les appeler.

pour le chauffage … ajoutez quelque chose comme

 try { Thread.sleep(100); // value is milliseconds } catch (InterruptedException e) { // no need to handle (in this example) } 

Cela réduira la charge du processeur de 100% (sur un cœur) à une valeur raisonnable;)