JAVA学习笔记(多线程二)——多线程的创建(一)
总共四种:
- 继承Thread类(重写run()方法)
- 实现Runnable接口(重写run()方法)
- 实现Callable接口(重写call()方法)
- 使用线程池(这也是我们开发中常用的)
多线程的创建方式一:
1.创建一个子类去继承Thread类
2.重写继承后run()方法
3.创建一个子类的对象
4.通过子类对象调用start()方法
多线程的创建方式二:
1.创建一个实现类去实现runnable接口
2.重写run()方法
3.创建一个实现类的对象
4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
5.通过Thread类的对象调用start()
比较创建线程的这两种方式
开发中:优先选择实现RunnabLe接口这种方式。
原因:
1.实现的方式没有类的单继承性的局限性
2.实现的方式更适合来处理多个线程有共享数据的情况。
联系: Thread类也实现了Runnable接口
**相同点:**两种方式都需要重写run()方法,将线程要执行的逻辑声明在run()方法中。
注意一:不能直接通过对象.方法(run方法)这样不是多线程而是单个线程(主线程)方法调用。(前面介绍过:一个Java应用程序java.exe,其实至少有三个线程:main()主线程,gc()垃圾回收线程,异常处理线程。当然如果发生异常,会影响主线程。)
注意二:启动一个线程,不可以还让已经start()的线程去执行。会报ILLegalThreadstateException。只能重新创建子类对象进行调用。
下面对比这两个创建方式:用一个我看视频学到的例子
创建三个窗口卖票,总票数为100张
继承的创建方式
class Windows extends Thread{
private static int ticket=100;
@Override
public void run() {
while (true){
if (ticket>0){
System.out.println(getName()+
":卖票,票号为:"+ticket);//Thread.currentThread().getName()本身继承了Thraed所以可以省略前面部分
ticket--;
}else {
break;
}
}
}
}
实现接口的创建方式
class Windows2 implements Runnable{
private static int ticket=100;
@Override
public void run() {
for (;;){
if (ticket>0){
System.out.println(Thread.currentThread().getName()+"卖票,票号为:"+ticket);
ticket--;
}else {
break;
}
}
}
}
一个测试类
public class WindowsTest {
public static void main(String[] args) {
// System.out.println("******************方式一***********************");
// Windows windows1=new Windows();
// Windows windows2=new Windows();
// Windows windows3=new Windows();
//
// windows1.setName("窗口1");
// windows2.setName("窗口2");
// windows3.setName("窗口3");
//
// windows1.start();
// windows2.start();
// windows3.start();
System.out.println("*****************方式二*******************");
Windows2 windowsinterface=new Windows2();
Thread thread1=new Thread(windowsinterface);
Thread thread2=new Thread(windowsinterface);
Thread thread3=new Thread(windowsinterface);
thread1.setName("窗口1");
thread2.setName("窗口2");
thread3.setName("窗口3");
thread1.start();
thread2.start();
thread3.start();
}
}
具体的执行结果由于每个人电脑不同,cpu处理线程是随机的的,结果执行顺序是不同的。