81,092
社区成员
发帖
与我相关
我的任务
分享
public class SynchronizedCode implements Runnable {
private int aa;
public SynchronizedCode(int aa){
this.aa = aa;
}
public void run() {
synchronized (this){
try {
System.out.println("@@"+aa);
Thread.sleep(aa);
System.out.println("----"+aa);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
SynchronizedCode sc1 = new SynchronizedCode(2000);
SynchronizedCode sc2 = new SynchronizedCode(1000);
Thread thread1 = new Thread(sc1);
Thread thread2 = new Thread(sc2);
thread1.start();
thread2.start();
}
}
public class SynchronizedCode implements Runnable {
private int aa;
public SynchronizedCode(int aa){
this.aa = aa;
}
public void run() {
synchronized (SynchronizedCode.class){
try {
System.out.println("@@##"+aa);
Thread.sleep(aa);
System.out.println("----"+aa);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
SynchronizedCode sc1 = new SynchronizedCode(2000);
SynchronizedCode sc2 = new SynchronizedCode(1000);
Thread thread1 = new Thread(sc1);
Thread thread2 = new Thread(sc2);
thread1.start();
thread2.start();
}
}
@@##2000
----2000
@@##1000
----1000public class SynchronizedCode
implements Runnable {
private Integer[] cc;
public void setCc(Integer[] cc) {
this.cc = cc;
}
public void run() {
for (int i =0;i<cc.length;i++) {
synchronized (this) {
try {
System.out.println("@@" + cc[i]);
Thread.sleep( cc[i]);
System.out.println("----" + cc[i]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
SynchronizedCode sc1 = new SynchronizedCode();
Integer[] cc= new Integer[2];
cc[0]=2000;
cc[1]=1000;
sc1.setCc(cc);
Thread thread1 = new Thread(sc1);
thread1.start();
}
}
@@2000
//休眠2000
----2000
@@1000
//休眠1000
----1000
SynchronizedCode sc1 = new SynchronizedCode(2000);
SynchronizedCode sc2 = new SynchronizedCode(1000);
Thread thread1 = new Thread(sc1);
Thread thread2 = new Thread(sc2);
thread1.start();
thread2.start();
老兄!你这是两个不同的线程,不同的SynchronizedCode 对象,各跑各的没有问题呀。
synchronized (this)这里的this要是同一个对象才行,需要将对象从类的外面传进去,你在这里写死,它永远不可能时同一个对象。