bonjour a tous
voila, j'ai un léger soucis.
mon programme crée des Thread, les thread, vont bien dans la méthode Run(), par exemple exécute un System.out.print(), mais, impossible de leur faire faire une boucle ou autre chose
aussi, si je stop met Thread avec la méthode stop(), je ne peut pas re-créer d'autre thread (exception), et aussi, elle ne s'arrete pas (remarqué grace au chrono
Donc, mes questions sont:
-comment stoppé une thread proprement (je doit pouvoir regré d'autre thread aprés)
/*-pourquoi mon chrono ne s'arret t'il pas lorsque normalement
while (!lab3.getText().equals(lab5.getText()))
devrait stopper (valoir false)*/ Résolu
- pourquoi mes thread n'exécute telle pas mes boucles???????
le code va surement vous premettre de mieux comprendre mon probleme.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//import javax.swing.event.*;
@SuppressWarnings("serial")
public class Ihmprocoswing extends JFrame implements ActionListener, Runnable {
/**
* @param args
*/
private int seconde, minute, heure;
public Thread th1;
public Thread th2;
public Thread th3;
public Thread th4;
public Thread th5;
public Thread th6;
public Thread th7;
public Thread th8;
public Thread chrono;
private JButton lancer;
private JButton stop;
private JLabel lab1;
private JLabel lab2;
private JLabel lab3;
private JLabel lab4;
private JLabel lab5;
private JLabel lab6;
private boolean passage = false;
private JComboBox cb;
int nbProc = Runtime.getRuntime().availableProcessors();// permet de savoir
// le nombre de
// processeur
String name = System.getProperty("os.name"); // donne le nom de l'os
String version = System.getProperty("os.version"); // donne la version de
// l'os
public Ihmprocoswing() {
setTitle("Test Processeur by Hannibal For hardware-pc");
setSize(650, 200);
setLocation(500, 500);
setLayout(new BorderLayout());
Color col = new Color(15, 212, 214);
JPanel pan1 = new JPanel(new GridLayout(1, 4, 3, 3));
JPanel pan2 = new JPanel(new GridLayout(1, 4, 3, 3));
// ===================NORTH========================
// lancer = new JButton(new ImageIcon("image/lancer2.png"));
lancer = new JButton("lancer");
lancer.addActionListener(this);
pan1.add(lancer);
stop = new JButton("stop"); // a mettre image
stop.addActionListener(this);
pan1.add(stop);
String combo[] = { "30 min", "1 Heure", "2 Heures", "4 Heures",
"6 Heures", "Infini" }; // contenu de la comboBox
cb = new JComboBox(combo);
cb.addActionListener(this);
pan1.add(cb);
lab1 = new JLabel("OS: " + name + " | " + version);
pan1.add(lab1);
// ===================SOUTH========================
lab2 = new JLabel("Temps écoulé: ");
pan2.add(lab2);
lab3 = new JLabel("00h00min00sec");
pan2.add(lab3);
lab4 = new JLabel("Temps Choisi: ");
pan2.add(lab4);
lab5 = new JLabel("00h30min00sec ");
pan2.add(lab5);
// ===================CENTER========================
lab6 = new JLabel("CENTER", JLabel.CENTER);
add(lab6, BorderLayout.CENTER);
// ================================================
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// fermeture fenetre
chrono = new Thread(this);
chrono.setName("chrono");
pan1.setBackground(col);
pan2.setBackground(col);
add(pan1, BorderLayout.NORTH);
add(pan2, BorderLayout.SOUTH);
setVisible(true);
}
@SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e) {
if (e.getSource() == lancer) {
// verif pour ne pas essayé de lancé 2
// fois les même Thread
if (passage == false) {
passage = true;
try {
// lancement des Thread
switch (nbProc) {
case 1:
th1 = new Thread(this);
th1.setName("th1"); // donne le nom th1 a la thread
th1.start();
break;// lancement d'un thread
case 2:
th1 = new Thread(this);
th2 = new Thread(this);
th1.setName("th1");
th2.setName("th2");
th1.start();
th2.start();
break;// lancement de 2 thread
case 3:
th1 = new Thread(this);
th2 = new Thread(this);
th3 = new Thread(this);
th1.setName("th1");
th2.setName("th2");
th3.setName("th3");
th1.start();
th2.start();
th3.start();
break;
case 4:
th1 = new Thread(this);
th2 = new Thread(this);
th3 = new Thread(this);
th4 = new Thread(this);
th1.setName("th1");
th2.setName("th2");
th3.setName("th3");
th4.setName("th4");
th1.start();
th2.start();
th3.start();
th4.start();
break;
case 5:
th1 = new Thread(this);
th2 = new Thread(this);
th3 = new Thread(this);
th4 = new Thread(this);
th5 = new Thread(this);
th1.setName("th1");
th2.setName("th2");
th3.setName("th3");
th4.setName("th4");
th5.setName("th5");
th1.start();
th2.start();
th3.start();
th4.start();
th5.start();
break;
case 6:
th1 = new Thread(this);
th2 = new Thread(this);
th3 = new Thread(this);
th4 = new Thread(this);
th5 = new Thread(this);
th6 = new Thread(this);
th1.setName("th1");
th2.setName("th2");
th3.setName("th3");
th4.setName("th4");
th5.setName("th5");
th6.setName("th6");
th1.start();
th2.start();
th3.start();
th4.start();
th5.start();
th6.start();
break;
case 7:
th1 = new Thread(this);
th2 = new Thread(this);
th3 = new Thread(this);
th4 = new Thread(this);
th5 = new Thread(this);
th6 = new Thread(this);
th7 = new Thread(this);
th1.setName("th1");
th2.setName("th2");
th3.setName("th3");
th4.setName("th4");
th5.setName("th5");
th6.setName("th6");
th7.setName("th7");
th1.start();
th2.start();
th3.start();
th4.start();
th5.start();
th6.start();
th7.start();
break;
case 8:
th1 = new Thread(this);
th2 = new Thread(this);
th3 = new Thread(this);
th4 = new Thread(this);
th5 = new Thread(this);
th6 = new Thread(this);
th7 = new Thread(this);
th8 = new Thread(this);
th1.setName("th1");
th2.setName("th2");
th3.setName("th3");
th4.setName("th4");
th5.setName("th5");
th6.setName("th6");
th7.setName("th7");
th8.setName("th8");
th1.start();
th2.start();
th3.start();
th4.start();
th5.start();
th6.start();
th7.start();
th8.start();
break;
}
} catch (Exception exc) {
System.out
.println("probleme dans le lancements des thread");
System.exit(0);
}
}
lab6.setText("En preparation");
switch (cb.getSelectedIndex()) {
case 0:
lab5.setText("00h30min00sec");
break;
case 1:
lab5.setText("01h00min00sec");
break;
case 2:
lab5.setText("02h00min00sec");
break;
case 3:
lab5.setText("04h00min00sec");
break;
case 4:
lab5.setText("06h00min00sec");
break;
case 5:
lab5.setText("INFINI");
break;
}
chrono.start();
passage = false;
} else {
if (e.getSource() == stop) {
try {
switch (nbProc) {
case 1:
th1.stop();
break;// stop d'un thread
case 2:
th1.stop();
th2.stop();
break;
case 3:
th1.stop();
th2.stop();
th3.stop();
break;
case 4:
th1.stop();
th2.stop();
th3.stop();
th4.stop();
break;
case 5:
th1.stop();
th2.stop();
th3.stop();
th4.stop();
th5.stop();
break;
case 6:
th1.stop();
th2.stop();
th3.stop();
th4.stop();
th5.stop();
th6.stop();
break;
case 7:
th1.stop();
th2.stop();
th3.stop();
th4.stop();
th5.stop();
th6.stop();
th7.stop();
break;
case 8:
th1.stop();
th2.stop();
th3.stop();
th4.stop();
th5.stop();
th6.stop();
th7.stop();
th8.stop();
break;
}
} catch (Exception exc) {
System.out.println("probleme dans les arret de thread");
System.exit(0);
}
lab5.setText("00h30min00sec");
cb.setSelectedIndex(0);
lab6.setText("Fin de la procedure d'arret");
}
}
}
@Override
public void run() {
// TODO Auto-generated method stub
String strj = Thread.currentThread().getName();// donne nom thread
// apellante
if (strj.equals("chrono")) {
while (!lab3.getText().equals(lab5.getText())) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
System.out.println("Probleme dans le temps du chrono");
}
seconde++;
if (seconde == 60) {
seconde = 00;
minute++;
}
if (minute == 60) {
minute = 00;
heure++;
}
lab3.setText(heure + "h" + minute + "min" + seconde + "sec");/*
* rafraichir
* le
* label
*/
}
}
Algotest algo = new Algotest();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Ihmprocoswing();
}
}
merci pour votre aide
edit: une petite vue de l'IHM avec quelque commentaire
probleme Résolu:
- arret du chronometre sur temps definie
Le jour où Microsoft fera des choses qui ne plantent pas, ça sera des clous ...
ok, mais, comme j'ai pas trouver ce que veux dire deprecier pour une methode.....
(apprecier invers de deprecier ? )
sinon pour le sleep, le 1 est juste la pour faire monté plus vite a 30min (je vais pas attendre 30min a chaque fois )
je mate ton lien tout de suite
edit: bon, je ne comprend pas (mon niveau d'anglais est un vrai probleme....)
pourrai tu m'expliquer?
je met a jour mon premier post avec une image de l'ihm et quelque commentaire, afin de vous aidez a la compréhension du probleme.
merci d'avance pour votre aide
Le jour où Microsoft fera des choses qui ne plantent pas, ça sera des clous ...
Sinon, Déprécier veut dire, ah ne (surtout) plus utiliser.
Utiliser stop pour arrêter un Thread peut provoquer des gros problèmed de corruption de données et autre.
public class monThread extends Thread {
private boolean _running = true;
public void run() {
while(_running) {
// Insert code here
if (condition de sortie)
_running = false;
}
}
}
Ceci suppose qu'il n'y a pas d'appel bloquant dans le code (ou pas d'appel bloquant pendant longtemps).
Imaginons maintenant que tu utilises un appel bloquant (sleep ou wait ou join ou autre sauf une lecture sur un inputstream).
public class monThread extends Thread {
public void run() {
while(true) {
// Insert code here
try {
this.sleep(30000); // Attente de 30 secondes
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Très important
break;
}
}
}
}
Avec ce code il suffit de faire t.interrupt() pour fermer proprement le thread.
Enfin, pour te convaincre que la ligne Thread.currentThread().interrupt(); est très importante, lance ce petit programme si tu ne le comprend pas très bien lance le en debug et parcours le pas à pas.
public class NestedLoops extends Thread {
private static boolean correct = true;
public void run() {
while (true) {
System.out.print(".");
System.out.flush();
for (int i = 0; i < 10; i++) {
System.out.print("#");
System.out.flush();
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
if (correct) Thread.currentThread().interrupt();
System.out.println();
System.out.println("Shut down inner loop");
break;
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
if (correct) Thread.currentThread().interrupt();
System.out.println();
System.out.println("Shut down outer loop");
break;
}
}
System.out.println("Shutting down thread");
}
private static void test() throws InterruptedException {
Thread t = new NestedLoops();
t.start();
Thread.sleep(6500);
t.interrupt();
t.join();
System.out.println("Shutdown the thread correctly");
}
public static void main(String[] args)
throws InterruptedException {
test();
correct = false;
test();
}
}
Voilà, j'espère avoir été assez claire. Si tu veux le fermer alors que le Thread bloque sur un appel read sur un inputStream ou associé, c'est un cas particulier que je peux te montrer.
Cool, je vais changer le code pour le chrono de mon démineur alors.
En gros maintenant il ne me reste plus que la partie réseaux à apprendre et le tour est jouer, je pourrai me lancer dans la progra de jeux en 2D multi-joueurs avec Java;).
Par contre ça va me demander de bonnes implémentations algorithmique, c'est justement ce qu'il me faut pour plus tard.
Ca vaudrait peut être le coup que j'intègre la partie sur l'arrêt lors d'une attente sur un Stream et que j'en fasse un tuto non (avec bien sûr plus d'explications, j'ai donnée la solution mais je n'ai pas expliqué pourquoi ici) ?
Ca vaudrait peut être le coup que j'intègre la partie sur l'arrêt lors d'une attente sur un Stream et que j'en fasse un tuto non (avec bien sûr plus d'explications, j'ai donnée la solution mais je n'ai pas expliqué pourquoi ici) ?
Bon ba j'essayerai de faire ça un de ces quatre. D'après les post qui se balladent sur le forum, un petit tuto sur le réseau et l'implémentation d'un système de chat serait pas mal non plus (même si plus long).
ok, alors, j'ai decider de ne pas arreter mes thread (je peux les laisser tournée en faite )
par contre, je ne comprend pas plusieurs autre chose....
quand je lance mes thread, pas de problème, pas charge proco monte a 100%, par contre, aprés, dés que j'arrête le test (les trhead tourne dans une boucle infini ) l'occupation processeur ne retombe que a 50%........
aussi, je voudrai savoir comment faire pour mettre une icone a coté du titre de la JFrame, et si il est possible de mettre ma methode actionPerformed en dehors de la class de mon IHM ?
sinon, question un peut specifique:
certain calcul processeur le font t'il plus chauffer que d'autre? car la, mon proco tourne a 100% mais ne chauffe pas beaucoup....
mon nouveaux code:
ma class ou va ce trouver l'algo de test
public class Algotest {
public Algotest() {
// le chrono bouffe bien en resource, a testé
}
public void test() {
// TODO Auto-generated method stub
String strj = Thread.currentThread().getName();// donne nom thread
if (strj.equals("th1")) {
// ici, si je veut lancer une boucle, elle n'est pas effectué
System.out.println("ici th1"); //executé
for(int i=0;i>=10;i++)
{
System.out.println("i= "+i); // pas executé
}
System.out.println("ici th1 2");//executé
}
if (strj.equals("th2")) {
// ici aussi
System.out.println("ici th2");//executé
for(int j=0;j>=10;j++)
{
System.out.println("j= "+j);// pas executé
}
System.out.println("ici th2 2");//executé
}
if (strj.equals("th3")) {
}
if (strj.equals("th4")) {
}
if (strj.equals("th5")) {
}
if (strj.equals("th6")) {
}
if (strj.equals("th7")) {
}
if (strj.equals("th8")) {
}
}
}
la class de l'IHM et le reste
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//import javax.swing.event.*;
@SuppressWarnings("serial")
public class Ihmprocoswing extends JFrame implements ActionListener, Runnable {
/**
* @param args
*/
private int seconde, minute;
private long heure;
private String temps;
public Thread th1;
public Thread th2;
public Thread th3;
public Thread th4;
public Thread th5;
public Thread th6;
public Thread th7;
public Thread th8;
public Thread chrono;
private JButton lancer;
private JButton stop;
private JLabel lab1;
private JLabel lab2;
public JLabel lab3;
private JLabel lab4;
public JLabel lab5;
private JLabel lab6;
private boolean autorisation = false;
private boolean passage = false;
private JComboBox cb;
int nbProc = Runtime.getRuntime().availableProcessors();// permet de savoir
// le nombre de
// processeur
String name = System.getProperty("os.name"); // donne le nom de l'os
String version = System.getProperty("os.version"); // donne la version de
// l'os
public Ihmprocoswing() {
// ===================IHM==================================
setTitle("Test Processeur by Hannibal For hardware-pc ");
setSize(650, 200);
setLocation(500, 500);
setLayout(new BorderLayout());
Color col = new Color(15, 212, 214);
JPanel pan1 = new JPanel(new GridLayout(1, 4, 3, 3));
JPanel pan2 = new JPanel(new GridLayout(1, 4, 3, 3));
// ===================NORTH========================
// lancer = new JButton(new ImageIcon("image/lancer2.png"));
lancer = new JButton("lancer");
lancer.addActionListener(this);
pan1.add(lancer);
stop = new JButton("stop"); // a mettre image
stop.addActionListener(this);
pan1.add(stop);
String combo[] = { "30 min", "1 Heure", "2 Heures", "4 Heures",
"6 Heures", "Infini" }; // contenu de la comboBox
cb = new JComboBox(combo);
cb.addActionListener(this);
pan1.add(cb);
lab1 = new JLabel("OS: " + name + " | " + version);
pan1.add(lab1);
// ===================SOUTH========================
lab2 = new JLabel("Temps écoulé: ");
pan2.add(lab2);
lab3 = new JLabel("00h00min00sec");
pan2.add(lab3);
lab4 = new JLabel("Temps Choisi: ");
pan2.add(lab4);
lab5 = new JLabel("00h30min00sec ");
pan2.add(lab5);
// ===================CENTER========================
lab6 = new JLabel("PRET", JLabel.CENTER);
add(lab6, BorderLayout.CENTER);
// ================================================
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// fermeture fenetre
chrono = new Thread(this);
chrono.setName("chrono");
pan1.setBackground(col);
pan2.setBackground(col);
add(pan1, BorderLayout.NORTH);
add(pan2, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == lancer) {
// verif pour ne pas essayé de lancé 2
// fois les même Thread
autorisation = true;
if (passage == false) {
try {
// lancement des Thread
switch (nbProc) {
case 1:
th1 = new Thread(this);
th1.setName("th1"); // donne le nom th1 a la thread
th1.start();
break;// lancement d'un thread
case 2:
th1 = new Thread(this);
th2 = new Thread(this);
th1.setName("th1");
th2.setName("th2");
th1.start();
th2.start();
break;// lancement de 2 thread
case 3:
th1 = new Thread(this);
th2 = new Thread(this);
th3 = new Thread(this);
th1.setName("th1");
th2.setName("th2");
th3.setName("th3");
th1.start();
th2.start();
th3.start();
break;
case 4:
th1 = new Thread(this);
th2 = new Thread(this);
th3 = new Thread(this);
th4 = new Thread(this);
th1.setName("th1");
th2.setName("th2");
th3.setName("th3");
th4.setName("th4");
th1.start();
th2.start();
th3.start();
th4.start();
break;
case 5:
th1 = new Thread(this);
th2 = new Thread(this);
th3 = new Thread(this);
th4 = new Thread(this);
th5 = new Thread(this);
th1.setName("th1");
th2.setName("th2");
th3.setName("th3");
th4.setName("th4");
th5.setName("th5");
th1.start();
th2.start();
th3.start();
th4.start();
th5.start();
break;
case 6:
th1 = new Thread(this);
th2 = new Thread(this);
th3 = new Thread(this);
th4 = new Thread(this);
th5 = new Thread(this);
th6 = new Thread(this);
th1.setName("th1");
th2.setName("th2");
th3.setName("th3");
th4.setName("th4");
th5.setName("th5");
th6.setName("th6");
th1.start();
th2.start();
th3.start();
th4.start();
th5.start();
th6.start();
break;
case 7:
th1 = new Thread(this);
th2 = new Thread(this);
th3 = new Thread(this);
th4 = new Thread(this);
th5 = new Thread(this);
th6 = new Thread(this);
th7 = new Thread(this);
th1.setName("th1");
th2.setName("th2");
th3.setName("th3");
th4.setName("th4");
th5.setName("th5");
th6.setName("th6");
th7.setName("th7");
th1.start();
th2.start();
th3.start();
th4.start();
th5.start();
th6.start();
th7.start();
break;
case 8:
th1 = new Thread(this);
th2 = new Thread(this);
th3 = new Thread(this);
th4 = new Thread(this);
th5 = new Thread(this);
th6 = new Thread(this);
th7 = new Thread(this);
th8 = new Thread(this);
th1.setName("th1");
th2.setName("th2");
th3.setName("th3");
th4.setName("th4");
th5.setName("th5");
th6.setName("th6");
th7.setName("th7");
th8.setName("th8");
th1.start();
th2.start();
th3.start();
th4.start();
th5.start();
th6.start();
th7.start();
th8.start();
break;
}
} catch (Exception exc) {
System.out
.println("probleme dans le lancements des thread");
System.exit(0);
}
}
switch (cb.getSelectedIndex()) {
case 0:
lab5.setText("00h30min00sec");
temps = "0h30min0sec";
break;
case 1:
lab5.setText("01h00min00sec");
temps = "1h0min0sec";
break;
case 2:
lab5.setText("02h00min00sec");
temps = "2h0min0sec";
break;
case 3:
lab5.setText("04h00min00sec");
temps = "4h0min0sec";
break;
case 4:
lab5.setText("06h00min00sec");
temps = "6h0min0sec";
break;
case 5:
lab5.setText("INFINI");
temps = "attendre";
break;
}
if (!passage) { // test si deja passer
passage = true;
chrono.start();
}
lab6.setText("Test en Cour");
} else {
if (e.getSource() == stop) {
autorisation = false;
seconde = 0;
minute = 0;
heure = 0;
lab3.setText(heure + "h" + minute + "min" + seconde + "sec");
lab5.setText("00h30min00sec");
cb.setSelectedIndex(0);
lab6.setText("PRET");
}
}
}
@Override
public void run() {
// TODO Auto-generated method stub
String strj = Thread.currentThread().getName();// donne nom thread
// apellante
// =============== Chrono=====================
if (strj.equals("chrono")) {
while (true) {
while (!lab3.getText().equals(temps)) {
if (autorisation) {
lab3.setText(heure + "h" + minute + "min" + seconde
+ "sec");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out
.println("Probleme dans le temps du chrono");
}
seconde++;
if (seconde == 60) {
seconde = 00;
minute++;
}
if (minute == 60) {
minute = 00;
heure++;
}
}
}
if (lab3.getText().equals(temps)) {
autorisation = false;
seconde = 0;
minute = 0;
heure = 0;
lab3
.setText(heure + "h" + minute + "min" + seconde
+ "sec");
lab5.setText("00h30min00sec");
cb.setSelectedIndex(0);
lab6.setText("Test Terminé / PRET");
}
}
}
// =================== Test=====================
if (strj.equals("th1") || strj.equals("th2") || strj.equals("th3")
|| strj.equals("th4") || strj.equals("th5")
|| strj.equals("th6") || strj.equals("th7")
|| strj.equals("th8")) {
while (autorisation) {
// Algotest algo = new Algotest();
// algo.test();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Ihmprocoswing();
}
}
merci d'avance pour votre aide
edit: des que je fais lancer....... stop la charge proco fait 100%......50% deja, bizarre, puis, si aprés je rappuis sur lancer, et bien la, la charge tombe a 0%
une idée?????
Le jour où Microsoft fera des choses qui ne plantent pas, ça sera des clous ...
le probleme principale ne vient pas de l'IHM, mais des Thread....
Le jour où Microsoft fera des choses qui ne plantent pas, ça sera des clous ...
[Help] Thread
× Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
× Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.