Java多线程创建

多线程创建
class B extends Thread {
private String threadName;
        public B(String name){
            this.threadName = name;
        }
        private int count = 0;
        public  void add(){
             ++count;
         }
            @Override
            public void run(){
                    for(int i = 0; i<2; ++i){
                        add();
                        System.out.println("thread "+Thread.currentThread().getName() 
                                +" is working " +i+" couter is " +(count));

                }
        }
}
public class RunnableDemo  {

    public static void main(String[] args){
        //Work work = new Work();
        B mythread11 = new B("mythread11");     
        B mythread12 = new B("mythread12");
        mythread11.start();
        mythread12.start();
        System.out.private
    }
}

结果:
这里写图片描述
注意到,线程名Thread-0、Thread-1不是自定义mythread11、mythread12而是内部定义的名称。这与上篇“java多线程1-多线程创建与线程同步”提到的下面所列举的代码:

Thead thread1 = new Thread(new Work(), “thread1”); 
Thread thread2 = new Thread(new Work(), “thread2”); 
thread1.start();
thread2.start();

上面代码有两个Work对象,对应两把锁,就是因为有两把对象锁(两把锁就使得两个线程独立,synchronized也就没什么意义),也这才出现上图那样的结果,上面的代码结果如下:
这里写图片描述
名称(thread-1\thread-2)是自定义的

参考:
http://blog.csdn.net/cangchen/article/details/45198069

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值