1.1线程新建
Mythread.java
package threadTest;
public class MyThread extends Thread{
@Override
public void run(){
super.run();
for (int i = 0; i < 100; i++){
System.out.println("MyThread:" + i);
}
}
}
Main.java
package threadTest;
public class main {
public static void main(String[] args){
MyThread myThread = new MyThread();
myThread.start();
MyThread myThread1 = new MyThread();
myThread1.start();
System.out.println("Has been ran");
}
}
因为 Runnable 接口中只有 run 方法,无法启动一个新的线程。所以借由 Thread 的构造,可以新建线程。
Runnable.java
package threadTest;
public class MyRunnable implements Runnable{
@Override
public void run(){
System.out.println("Runnable");
}
}
Run.java
package threadTest;
public class Run {
public static void main(String[] args) {
Runnable runnable = new MyRunnable();
Thread thread = new Thread(runnable); //runnable has no 'start' method, so use thread to decorate(compact).
thread.start();
System.out.println("done");
}
}
-
调用 start() 是通知线程规划器,目标线程已经准备好了,线程规划器可以安排一个时间来启动目标线程,属于异步执行。
-
调用 run() 时,是直接执行对应的目标线程的代码段,执行完 run() 中的代码才会继续下一步,属于同步执行。