Hallo,
Ik heb een vraagje over threads en hopelijk kunnen jullie mij hierbij helpen.
Dit voorbeeldje heb ik van het internet:
Simpel voorbeeldje, het print "a en b " n keer.
output: ababab....................
ok, nou wil ik het volgende:
In de PrintChar functie de forloop zetten die nou in de run functie zit en de PrintChar
aanroepen in run, zoals hieronder:
Is dit mogelijk? zoja, hoe doe ik dit?
Ik heb een vraagje over threads en hopelijk kunnen jullie mij hierbij helpen.
Dit voorbeeldje heb ik van het internet:
Java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
| class PrintChar extends Thread { private char charToPrint; private int times; Thread myThread; private boolean frozen = true; //Contruct thread to print ii++ public PrintChar(char charToPrint,int times){ this.charToPrint = charToPrint; this.times = times; /* for(int n=0;n <=times;n++){ System.out.print(charToPrint); }*/ } public void run(){ for(int n=0;n <=times;n++){ System.out.print(charToPrint); yield();//pause for other thread // try { // sleep((int)(Math.random() * 1)); // } catch (InterruptedException e) {} } } } public class TestThread { //main method public static void main(String[] opt) { //create object+threads StopWatch tijd = new StopWatch(); PrintChar printA = new PrintChar('a', 58); PrintChar printB = new PrintChar('b', 50); //PrintChar printC = new PrintChar('c', 25); //PrintNum print666 = new PrintNum(60); //PrintNum print667 = new PrintNum(90); //Sstart treads tijd.beginTime(); printA.start(); printB.start(); //printC.start(); //print666.start(); //print667.start(); tijd.stopTime(); tijd.diffTime(); } } |
Simpel voorbeeldje, het print "a en b " n keer.
output: ababab....................
ok, nou wil ik het volgende:
In de PrintChar functie de forloop zetten die nou in de run functie zit en de PrintChar
aanroepen in run, zoals hieronder:
Java:
1
2
3
4
5
6
7
8
9
10
11
| public PrintChar(char charToPrint,int times){ this.charToPrint = charToPrint; this.times = times; /* for(int n=0;n <=times;n++){ System.out.print(charToPrint); }*/ } public void run(){ PrintChar(charToPrint, times); yield();//pause for other thread |
Is dit mogelijk? zoja, hoe doe ik dit?