多线程创建
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)是自定义的