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

java中线程sleep和加锁synchronized 关键字的一些区别

2011-04-15 23:55 495 查看
第一种代码:没有synchronized

public class ThreadTest1Test {  //main函数

public static void main(String[] args) {
ThreadTest2 r = new ThreadTest2();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();

}
}
//线程函数
public class ThreadTest2 implements Runnable {

private static int temp = 0;

public void run() {
this.add();

}

public  void add() {
temp++;
try {

Thread.sleep(10);
} catch (InterruptedException e) {

}
System.out.println(Thread.currentThread().getName() + " " + temp);

}
}

//此时输出的结果是
//Thread-1 2
//Thread-0 2


加上synchronized

public class ThreadTest1Test {  //main方法

public static void main(String[] args) {
ThreadTest2 r = new ThreadTest2();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();

}
}
public class ThreadTest2 implements Runnable {//线程函数

private static int temp = 0;

public void run() {
this.add();

}

public  synchronized void add() {
temp++;
try {

Thread.sleep(10);
} catch (InterruptedException e) {

}
System.out.println(Thread.currentThread().getName() + " " + temp);

}
}

//结果为
//Thread-1 1
//Thread-0 2


第二种

public class ThreadTest1Test {  //main方法

public static void main(String[] args) {

Thread t1 = new Thread(new ThreadTest2());
Thread t2 = new Thread(new ThreadTest2());

t1.start();
t2.start();

}
}
public class ThreadTest2 implements Runnable {//线程函数

private static int temp = 0;

public void run() {
this.add();

}

public  synchronized void add() {
temp++;
try {

Thread.sleep(10);
} catch (InterruptedException e) {

}
System.out.println(Thread.currentThread().getName() + " " + temp);

}
}

//输出的结果
//Thread-0 2
//Thread-1 2


注意比较第一种和第二种输出结果上的区别

特别是第二种 在创建线程类的时候是创建两个线程

而第一种 在创建线程类的时候创建一个
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: