多线程

多线程的实现
class MyThread extends Thread{
private String name;//定义类中的属性
public MyThread(String name ){//定义构造方法
this.name=name;
}

@override
public void run(){//覆写run()方法,作为线程的主操作方法
for(int x = 0;x < 200 ;x ++){
System.out.print(this.name + "--->" +x);

}

}


}
public class TestDemon{//主类
public  static  void main(String [] args){
MyThread mt1 =new MyThread("线程A");
MyThread mt2 =new MyThread("线程B");
MyThread mt3 =new MyThread("线程C");

mt1.run ();
mt2.run ();
mt3.run ();
}




}


  public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();


        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);


        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }


    private native void start0();


//实现方式二 实现Runable接口
class MyThread implements Runable{
private String name;//定义类中的属性
public MyThread(String name ){//定义构造方法
this.name=name;
}

@override
public void run(){//覆写run()方法,作为线程的主操作方法
for(int x = 0;x < 200 ;x ++){
System.out.print(this.name + "--->" +x);

}

}


}
public class TestDemon{//主类
public  static  void main(String [] args){
MyThread mt1 =new MyThread("线程A");
MyThread mt1 =new MyThread("线程B");
MyThread mt1 =new MyThread("线程C");
/
*不管何种情况下,如果想要启动多线程一定不要依靠Thread类完成
*Thread类提供的构造方法 :public Thread(Runnable target),接收的是Runnable接口对象

*
/
new Thread(mt1).start();
new Thread(mt2).start();
new Thread(mt2).start();


}
三。区别:
Thread 类是Runnable接口的子类,使用Runnable 接口实现多线程可以避免单继承的局限
Runnable 接口实现的多线程可以比Thread类实现的多线程更加清楚的描述数据的流向






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值