思考:main方法为主线程,其他线程一般从main开始创建,一旦创建,线程start()启动后,线程内的执行顺序将交由调度器管辖,不过我们可以为线程设置优先权。
多线程实现方式
-
extends Thread
重写run()方法,通过start()启动线程。 -
class implements runable
@overwrite run()方法,启动方式为new Thread(class,“名字”).start();
两种方法比较:需要多重继承时选择方法2,并且方法2中的一个数据可以同时给由同一个类创建的多个线程对象共享,应用例子:卖票窗口。
public class neaThread implements Runnable {
private int i = 200; //一共200张票需要卖出
public static void main(String[] args) throws InterruptedException {
System.out.println("main start");
neaThread t = new neaThread();
new Thread(t, "窗口1").start();
new Thread(t, "窗口2").start();
new Thread(t, "窗口3").start();//一共三个窗口卖票
System.out.println("main end");
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "start");
while(i>0) {
System.out.println(Thread.currentThread().getName()+"剩余票数为" + i--);
}
}
}
执行结果:三个窗口共享200张票一起卖,。