创建子线程类并实现Runnable接口
public class MyThread implements Runnable {
/**
* 创建第二种线程方式
* 实现Runnable接口并重写run()方法
*/
@Override
public void run() {
for (int i=1;i<=10;i++){
System.out.println(Thread.currentThread().getName() + "--->" + i);
}
}
}
测试类
public static void main(String[] args) {
//创建子线程
MyThread mt = new MyThread();
Thread t = new Thread(mt,"子线程");
t.start();
//主线程也打印1-10数字
for (int i=1;i<=10;i++){
System.out.println(Thread.currentThread().getName() + "----->" + i);
}
}
第二个线程方式买火车票
售票类
public class BuyTicketThread implements Runnable{
int ticketNum=10;
@Override
public void run() {
for (int i=1;i<=100;i++) {
if (ticketNum > 0) {
System.out.println("我在" + Thread.currentThread().getName() + "买到了" + (ticketNum--) + "票");
}
}
}
}
测试类
public static void main(String[] args) {
//定义一个线程对象
BuyTicketThread t= new BuyTicketThread();
//窗口1买票
Thread t1=new Thread(t,"窗口1");
t1.start();
//窗口1买票
Thread t2=new Thread(t,"窗口2");
t2.start();
//窗口1买票
Thread t3=new Thread(t,"窗口3");
t3.start();
}
思考:
1.实际开发中,方式1继承Thread还是方式2实现Runnable接口这种方式多呢?答案是-->方式2
2.方式2的共享资源的能力也会强一些,不需要非得加个static来修饰
3.Thread类和Runnable接口有什么联系?
方式2的线程类-->实现Runnable接口
方式1的线程类-->继承Thread类-->实现Runnable接口