[size=x-large]有两种线程类分别是Thread和线程接口Runnable,CPU在读取线程类经过编译后的机器语言的时候,cup 会快速交错的去读取各个开启的线程。具体的流程可以如下:
1 把线程类的代码经过虚拟机转换成cpu识别的机器语言,(载入内存,此时cpu运行这些机器语言)
2 cpu开始交错快速执行各个线程,也可以通过代码来控制线程的执行情况。比如:
在一个线程执行的某一点处可以执行sleep()方法暂停这个线程,也可以在执行过程中执行yield()方法来让这个线程处于可以被执行状态了,(可以说成是在此处重新执行了这个线程)[/size]
测试代码:1 public class TestRunnable implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
TestRunnable runnable = new TestRunnable();
[size=xx-large]Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);[/size]
thread2.yield();
thread2.start();
try {
thread2.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread1.start();
}
}
2 public class TestThread extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
TestThread thread = new TestThread();
TestThread thread1=new TestThread();
thread.start();
thread1.start();
}
}
1 把线程类的代码经过虚拟机转换成cpu识别的机器语言,(载入内存,此时cpu运行这些机器语言)
2 cpu开始交错快速执行各个线程,也可以通过代码来控制线程的执行情况。比如:
在一个线程执行的某一点处可以执行sleep()方法暂停这个线程,也可以在执行过程中执行yield()方法来让这个线程处于可以被执行状态了,(可以说成是在此处重新执行了这个线程)[/size]
测试代码:1 public class TestRunnable implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
TestRunnable runnable = new TestRunnable();
[size=xx-large]Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);[/size]
thread2.yield();
thread2.start();
try {
thread2.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread1.start();
}
}
2 public class TestThread extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
TestThread thread = new TestThread();
TestThread thread1=new TestThread();
thread.start();
thread1.start();
}
}