Sina.iRoid
شنبه 22 آذر 1393, 10:44 صبح
سلام دوستان.
اگر امکانش هست میشه در مورد اجرای ترد های زیر یه توضیحی بدین!؟ من درست متوجه نمیشم که چی میشه. ممنون.
کد کلاس Clicker
public class Clicker implements Runnable{
int click = 0;
Thread thread;
private volatile boolean running = true;
//Constructor
public Clicker(int p) {
thread = new Thread(this);
thread.setPriority(p);
}
@Override
public void run() {
while (running) {
click++;
}
}
public void stop(){
running = false;
}
public void start(){
thread.start();
}
}
کد کلاس اصلی:
public class MainClassTest {
public static void main(String[] args) {
Thread.currentThread().setPriority(Thread.MAX_PRIO RITY);
Clicker hi = new Clicker(Thread.NORM_PRIORITY + 2);
Clicker lo = new Clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
//wait for child thread to terminate
try {
hi.thread.join();
lo.thread.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught.");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}
}
و این هم خروجی برنامه:
Low-priority thread: 159920241
High-priority thread: 207377818
من متوجه این کد نمیشم؟ Volatile برای چی هست؟
private volatile boolean running = true;
ممنون میشم اگر راهنماییم کنید.
اگر امکانش هست میشه در مورد اجرای ترد های زیر یه توضیحی بدین!؟ من درست متوجه نمیشم که چی میشه. ممنون.
کد کلاس Clicker
public class Clicker implements Runnable{
int click = 0;
Thread thread;
private volatile boolean running = true;
//Constructor
public Clicker(int p) {
thread = new Thread(this);
thread.setPriority(p);
}
@Override
public void run() {
while (running) {
click++;
}
}
public void stop(){
running = false;
}
public void start(){
thread.start();
}
}
کد کلاس اصلی:
public class MainClassTest {
public static void main(String[] args) {
Thread.currentThread().setPriority(Thread.MAX_PRIO RITY);
Clicker hi = new Clicker(Thread.NORM_PRIORITY + 2);
Clicker lo = new Clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
//wait for child thread to terminate
try {
hi.thread.join();
lo.thread.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught.");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}
}
و این هم خروجی برنامه:
Low-priority thread: 159920241
High-priority thread: 207377818
من متوجه این کد نمیشم؟ Volatile برای چی هست؟
private volatile boolean running = true;
ممنون میشم اگر راهنماییم کنید.