代码如下:
疑问:对于方式一和方式二 区别就是在new Thread()时候,方式一是传递了同一个 Processor对象p,而方式二是new了两个Processor对象,请问单独从这点来说 对于后续 启动两个线程有什么不同之处吗?
即使new Thread是传递同一个Processor对象p t1.start() 和 t2.start() 都会开启两个线程。
而这种方式 也是 会开启两个线程 这两种方式有什么区别吗???
Thread t1 = new Thread(new Processor());
Thread t2 = new Thread(new Processor());
public class synchronized {
public static void main(String[] args) throws InterruptedException {
//方式一
MyClass m = new MyClass();
Processor p = new Processsor(m);
Thread t1 = new Thread(p);
Thread t2 = new Thread(p);
t1.start();
t2.start();
//方式二-----------------------------------------------------------------
Thread t1 = new Thread(new Processor());
Thread t2 = new Thread(new Processor());
t1.start();
t2.start();
}
}
class Processsor implements Runnable {
MyClass mc;
public Processor() {}
public Processor(MyClass mc) {
this.mc = mc;
}
@Override
public void run() {
if ("t1".equals(Thread.currentThread().getName())) {
MyClass02.m1(); //类锁
}
if ("t2".equals(Thread.currentThread().getName())) {
MyClass02.m2();
}
}
}
class MyClass {
public synchronized static void m1() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("m1........");
}
public synchronized static void m2() {
System.out.println("m2........");
}
}
anet
相关分类