Java多线程创建

来源:互联网 发布:java发送邮件的jar包 编辑:程序博客网 时间:2024/06/03 23:50

多线程创建

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
原创粉丝点击