1 // 创建线程方式2,是实现runnable ,重写run方法,执行线程需要丢入runnable接口实现类,调用start()
2 public class TestThread3 implements Runnable {
3 @Override
4 public void run() {
5 // run方法线程体
6 for (int i = 0; i < 20 ; i++) {
7 System.out.println("我在看代码---" + i);
8 }
9 }
10
11 public static void main(String[] args) {
12
13 // 创建一个runnable接口的实现对象
14 TestThread3 testThread3 = new TestThread3();
15 // 创建线程对象,通过线程对象来开启线程,代理
16 /*Thread thread = new Thread(testThread3);
17 thread.start();*/
18 new Thread(testThread3).start();
19
20 // main线程,多线程
21 for (int i = 0; i < 20 ; i++) {
22 System.out.println("我在学习多线程---" + i);
23 }
24 }
25
Thread类是在java.lang包中定义的。一个类只要继承了Thread类同时覆写了本类中的
run()方法就可以实现多线程操作了,但是一个类只能继承一个父类,这是此方法的局限。
在使用Runnable定义的子类中没有start()方法,只有Thread类中才有。
推荐使用Runnable:避免单继承局限性,灵活方便,方便同一个对象被多个线程同时使用
实例:买票
1 public class TestThread4 implements Runnable{
2
3 // 票数
4 private int ticketNums = 10;
5 @Override
6 public void run() {
7 while(true) {
8 if(ticketNums <= 0) {
9 break;
10 }
11 try {
12 Thread.sleep(200);
13 } catch (InterruptedException e) {
14 e.printStackTrace();
15 }
16 System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNums-- + "张票");
17 }
18 }
19
20 public static void main(String[] args) {
21 TestThread4 ticketGetter = new TestThread4();
22 // 创建三个线程并开启
23 new Thread(ticketGetter,"小明").start();
24 new Thread(ticketGetter,"老师").start();
25 new Thread(ticketGetter,"黄牛").start();
26
27 }
28
29
30
31
32
33
结果分析
如图中所示,不同的线程买到了同一张票,这样在现实生活中是不可取的。
// 创建线程方式2,是实现runnable ,重写run方法,执行线程需要丢入runnable接口实现类,调用start()
public class TestThread3 implements Runnable {
@Override
public void run() {
// run方法线程体
for (int i = 0; i < 20 ; i++) {
System.out.println("我在看代码---" + i);
}
}
public static void main(String[] args) {
// 创建一个runnable接口的实现对象
TestThread3 testThread3 = new TestThread3();
// 创建线程对象,通过线程对象来开启线程,代理
/*Thread thread = new Thread(testThread3);
thread.start();*/
new Thread(testThread3).start();
// main线程,多线程
for (int i = 0; i < 20 ; i++) {
System.out.println("我在学习多线程---" + i);
}
}
}