Sina.iRoid
شنبه 19 مهر 1393, 12:44 عصر
سلام. این کد هایی است که من نوشتم:
کلاس MyThread:
public class MyThread implements Runnable{
Thread t;
//Constructor
public MyThread() {
//Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
//Start the thread
t.start();
}
@Override
public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println("Child thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting Child thread.");
}
}
کلاس اصلی:
public class DriverClass{
public static void main(String[] args) {
new MyThread();
try {
for (int i = 5; i > 0; i--) {
System.out.println("Main thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main interrupted.");
}
System.out.println("Main thread exiting.");
}
}
خروجی برنامه:
Child thread: Thread[Demo Thread,5,main]
Main thread: 5
Child thread: 5
Child thread: 4
Main thread: 4
Child thread: 3
Child thread: 2
Main thread: 3
Child thread: 1
Exiting Child thread.
Main thread: 2
Main thread: 1
Main thread exiting.
دوستان من اصلا متوجه نمیشم که چه طور اجرا میشه. در کلاس Mythread چرا از کانستراکتور و this استفاده کرده؟؟
اگر یه توضیح کمی راجع به این کد بدین ممنون مشم. من تازه این بخش و دارم می خونم درست متوجه نمیشم.
ممنون.
کلاس MyThread:
public class MyThread implements Runnable{
Thread t;
//Constructor
public MyThread() {
//Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
//Start the thread
t.start();
}
@Override
public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println("Child thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting Child thread.");
}
}
کلاس اصلی:
public class DriverClass{
public static void main(String[] args) {
new MyThread();
try {
for (int i = 5; i > 0; i--) {
System.out.println("Main thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main interrupted.");
}
System.out.println("Main thread exiting.");
}
}
خروجی برنامه:
Child thread: Thread[Demo Thread,5,main]
Main thread: 5
Child thread: 5
Child thread: 4
Main thread: 4
Child thread: 3
Child thread: 2
Main thread: 3
Child thread: 1
Exiting Child thread.
Main thread: 2
Main thread: 1
Main thread exiting.
دوستان من اصلا متوجه نمیشم که چه طور اجرا میشه. در کلاس Mythread چرا از کانستراکتور و this استفاده کرده؟؟
اگر یه توضیح کمی راجع به این کد بدین ممنون مشم. من تازه این بخش و دارم می خونم درست متوجه نمیشم.
ممنون.