线程的两个创建方法

1.继承Thread类

2.实现Runnable接口


一、继承Thread类

说明:继承Thread类,重写run()方法,调用start()方法启动线程。

public class Example02 {
public static void main(String[] args) {
MyThread myThread=new MyThread();
myThread.start();
while(true){
System.out.println("main方法在运行");
}
}
}
class MyThread extends Thread{
@Override
public void run() {
while(true){
System.out.println("MyThread的方法在运行");
}
}
}

结果:


二、实现Runable接口

说明:java中类只能单继承,当需要继承其他类又需要实现接口时,可以实现Runable接口来实现多线程。

Thread类中有Thread(Runable target)的构造函数,只需要传递一个Runable的实例对象就可以创建线程了。

public class Example03 {
public static void main(String[] args) {
MyThread1 myThread=new MyThread1();
Thread thread=new Thread(myThread);
thread.start();
while(true){
System.out.println("main的程序正在运行");
}
}
}
class MyThread1 implements Runnable{
public void run(){
while(true){
System.out.println("MyThread类的run方法在运行");
}
}

}

两个线程的区别:

每使用一次new Thread()就会创建一个实例对象,所有的数据都是独立的,相当于创建了多个程序,当需要共享资源时,就会要求在一个程序中实现多线程,实现Runnable接口时,使用的是new Thread(Runnable target),只使用一个对象,从而实现资源的共享。

Runnable的优势:

实现资源的共享,体现了面向对象的思想。

可以避免单继承带来的局限性。

Runnable()实现资源共享的例子:

package study;
public class Example05 {
public static void main(String[] args) {
TicketWindow tw=new TicketWindow();
    new Thread(tw,"窗口1").start();
    new Thread(tw,"窗口2").start();
    new Thread(tw,"窗口3").start();
    new Thread(tw,"窗口4").start();

}


}
class TicketWindow implements Runnable{
private int tickets=100;
@Override
public void run() {

// TODO Auto-generated method stub
while(true){
if(tickets>0){
Thread th=Thread.currentThread();
String th_name=th.getName();
System.out.println(th_name+"正在发售第"+tickets--+"张票");
}
}
}
}

结果:


该例子实现了tickets资源的共享。

但是当把int tickets=100;放在run内部的时候,就会造成即资源不共享的情况,和继承Thread类时的问题相似的结果,原因是每次都调用了run()方法

实例:

package study;
public class Example05 {
public static void main(String[] args) {
TicketWindow tw=new TicketWindow();
    new Thread(tw,"窗口1").start();
    new Thread(tw,"窗口2").start();
    new Thread(tw,"窗口3").start();
    new Thread(tw,"窗口4").start();

}


}
class TicketWindow implements Runnable{

@Override
public void run() {
int tickets=100;
// TODO Auto-generated method stub
while(true){
if(tickets>0){
Thread th=Thread.currentThread();
String th_name=th.getName();
System.out.println(th_name+"正在发售第"+tickets--+"张票");
}
}
}
}

结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值