Professional Documents
Culture Documents
Java Threads
Java Threads
Thread?
Threading
CPU Multitasking
Java thread mainthread
Java (start)JVM mainthread methodmain()
thread JVM thread thread
garbagecollection,thread objectfinalization thread
memory,filehandlers preprocessstate
thread UI
CPU I/O thread
CPU controller
()
Thread
6/26/20063:54PM
Page1
ThreadsinJava
thread
thread Java thread
(workingthread) threadobject thread workingthread
threadobject JVM
thread thread(start)
thread
thread methodrun()
() thread thread
deadstate methodrun() NotRunnable method
sleep() thread methodwait() thread blockingI/O
6/26/20063:54PM
Page2
ThreadsinJava
run() for/loop 10
thread sleep()
for/loop DONE!
thread
public class TwoThreadsTest {
public static void main(String[] args) {
new SimpleThread("Bangkok").start();
new SimpleThread("Chaing Mai").start();
}
}
6/26/20063:54PM
0:Bangkok
0:ChiangMai
1:Bangkok
1:ChiangMai
2:Bangkok
3:Bangkok
2:ChiangMai
3:ChiangMai
4:Bangkok
4:ChiangMai
5:Bangkok
6:Bangkok
5:ChiangMai
6:ChiangMai
7:Bangkok
7:ChiangMai
8:Bangkok
8:ChiangMai
9:ChiangMai
9:Bangkok
DONE!ChiangMai
DONE!Bangkok
Page3
ThreadsinJava
thread interfaceRunnable
public class SimpleThread2 implements Runnable {
private String name;
public SimpleThread2(String str) {
name = str;
}
public void run() {
for(int i = 0; i < 10; i++) {
System.out.printf("%d: %s%n", i, this.name);
try {
Thread.sleep((long)(Math.random() * 1000));
}
catch(InterruptedException e) {}
}
System.out.printf("DONE! %s%n", this.name);
}
}
6/26/20063:54PM
Page4