您的位置:首页 > 编程语言 > Java开发

Java线程同步实例

2016-11-03 21:50 411 查看


Java线程同步实例

package lab8.wu;
public class mythread {
public static void main(String[] args) {
new Create("thread1");
new Create("thread2");
}
}
class Create implements Runnable {
static int a = 10;
private Thread t;

public Create(String name) {
t = new Thread(this);
t.setName(name);
t.start();
}

public void run() {
System.out.println("进入同步前"+t.getName()+" "+a);
synchronized (this) {
Thread t = Thread.currentThread();
for (int i = 0; i < 3; i++) {
a++;
System.out.println(t.getName() + "  " + i+"  a="+a);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
}


运行结果,thread1和thread2是乱序的,synchronized并未起到作用,synchronized锁住的是两个对象,彼此之间不造成影响:



对比代码:

package lab8.wu;

public class mythread2 {
public static void main(String[] args) {
Create2 create2=new Create2("th");
Thread th1=new Thread(create2,"thread1");
Thread th2=new Thread(create2,"thread2");
th1.start();
th2.start();
}
}

class Create2 implements Runnable {
static int a = 10;
private Thread t;

public Create2(String name) {
t = new Thread(this);
t.setName(name);
t.start();
}

public void run() {
Thread t = Thread.currentThread();
System.out.println("进入同步前"+t.getName()+" "+a);
synchronized (this) {
for (int i = 0; i < 3; i++) {
a++;
System.out.println(t.getName() + "  " + i+"  a="+a);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
}


运行结果,synchronized起到作用,在synchronized中的代码同一时间不能被不同的线程同时进入:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: