synchronized 的作用不是在线程访问该类的对象是把对象锁定等该语句执行完了以后才解锁的吗 为什么这样写 输出结果还是同时执行的呢 菜鸟学线程 求高手解答public class TestSynchronized {
public static void main(String[] args) {
T t1 = new T("t1");
T t2 = new T("t2");
t1.start();
t2.start();
}
public void run2() {
}
}
class T extends Thread { private static int num = 0; T(String n) {
super(n);
}
public void run() {
synchronized(this) {
num++;
try {
Thread.sleep(1000);
} catch(InterruptedException e) {}
System.out.println(getName() + "------" + num);
}
}
}
public static void main(String[] args) {
T t1 = new T("t1");
T t2 = new T("t2");
t1.start();
t2.start();
}
public void run2() {
}
}
class T extends Thread { private static int num = 0; T(String n) {
super(n);
}
public void run() {
synchronized(this) {
num++;
try {
Thread.sleep(1000);
} catch(InterruptedException e) {}
System.out.println(getName() + "------" + num);
}
}
}
public class TestSynchronized {
public static void main(String[] args) {
TestSynchronized o = new TestSynchronized();
T t1 = new T("t1",o);
T t2 = new T("t2",o);
t1.start();
t2.start();
}
public void run2() {
}
}
class T extends Thread { private static int num = 0;
TestSynchronized o; T(String n,TestSynchronized target) {
super(n);
o=target;
}
public void run() {
synchronized(o) {
num++;
try {
Thread.sleep(1000);
} catch(InterruptedException e) {}
System.out.println(getName() + "------" + num);
}
}
}
T t1 = new T("t1");
T t2 = new T("t2");
t1.start();
t2.start();
}
}
class T extends Thread {
TT ts = new TT();
T(String n) {
super(n);
}
public void run() {
ts.run2();
}
}
class TT {
private static int num = 0;
public void run2() {
synchronized(this) {
num++;
try {
Thread.sleep(1000);
} catch(InterruptedException e) {}
System.out.println("------" + num);
}
}
}
Timer timer = new Timer();
public static void main(String[] args) {
TestSync test = new TestSync();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run(){
timer.add(Thread.currentThread().getName());
}
}class Timer{
private static int num = 0;
public synchronized void add(String name){
//synchronized (this) {
num ++;
try {Thread.sleep(1);}
catch (InterruptedException e) {}
System.out.println(name+", 你是第"+num+"个使用timer的线程");
//}
}
}
为什么这样用就可以
你这样可以,是因为你创建的两个线程访问的是同一个对象的synchronized的方法, 所以可以。之前不可以,是因为你创建的两个线程访问了两个不同的对象, 每一个线程都访问自己的对象里面的方法,所以锁不住。 如果你想一开始的那个例子也有同步效果的话, 你应该把那个同步块提出来, 把它变成一个静态的同步方法, 就能锁住了。楼主明白??
你的第一次写法,syncrhonized(this)就是每个线程自己锁自己(和别的线程没有任何干涉),所以达不到同步的效果public class TestSync implements Runnable {
Timer timer = new Timer();
public static void main(String[] args) {
TestSync test = new TestSync();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run(){
syncronized(this) { //没有这里也不可以
timer.add(Thread.currentThread().getName());
}
}
}
这个例子可以(上面修改后),是因为t1和t2共同使用一个test楼主好好理解一下,第一次为什么没有共同使用一个对象?为什么上面这段程序是共同使用一个对象?