Java的线程机制是抢占式的,这表示调度机制会周期性地中断线程,将上下文切换到另一个线程,从而为每个线程都提供时间片,使得每个线程都会分配到数量合理地时间去驱动它的任务。
线程可以驱动任务,描述任务地方式可以由Runnable接口来提供。定义任务:实现Runnable接口并编写run()方法。通常run()是无限循环。
##Thread
将Runnable对象转变为工作任务地传统方式是把他提交给一个Thread构造器。Thread构造器调用Thread对象的start()方法为该线程执行必须的初始化操作,然后调用Runnable的run()方法,以便在这个新线程中启动该任务。
练习1
package four;
public class Solution {
public static void main(String[] args) {
// TODO Auto-generated method stub
while (true) {
Thread thread = new Thread(new MultiProcess());
thread.start();
System.out.println("Waiting");
}
}
}
class MultiProcess implements Runnable {
private int count = 3;
public MultiProcess() {
System.out.println("Start");
}
public void run() {
while (count-- > 0) {
System.out.println("hello, world" + count);
Thread.yield();
}
System.out.println("End");
}
}
输出结果
练习2
package five;
public class Solution {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 0; i <= 100; ++i) {
Thread thread = new Thread(new Fib(i));
thread.start();
}
}
}
class Fib implements Runnable {
private int n = 0;
private int fibonacci(int n) {
if (n == 0)
return 0;
if (n == 1)
return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
public Fib(int n) {
this.n = n;
}
public void run() {
for (int i = 0; i <= n; ++i) {
System.out.println(this.fibonacci(i));
Thread.yield();
}
}
}