for (inti=0; i < 100; i++) { System.out.println("Main Thread" + i); } }
}
classRunner1implementsRunnable { @Override publicvoidrun() { for (inti=0; i < 100; i++) { System.out.println("Runner1" + i); } } }
在java8中也可以利用Lambda表达式写成如下格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
public class T {
public static void main(String[] args) { //Runnable 是函数接口 可以使用Lambda表达式书写 Thread t = new Thread(() -> { for (int i = 0; i < 100; i++) { System.out.println("Runner1" + i); } }); t.start();
for (int i = 0; i < 100; i++) { System.out.println("Main Thread" + i); }
} }
线程状态转换
线程控制基本方法
sleep()
静态方法,时当前线程进入阻塞状态
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicstaticvoidsleep(long millis, int nanos) throws InterruptedException { if (millis < 0) { thrownewIllegalArgumentException("timeout value is negative"); }
if (nanos < 0 || nanos > 999999) { thrownewIllegalArgumentException( "nanosecond timeout value out of range"); }