这两个线程方式有什么区别高手帮忙
package icrement;public class Counter { protected long value = 0; public long getValue() {
return value;
}
public long increase(){
synchronized (this) {
this.value += 10;
return value;
}
}
}
package icrement;public class Thread1 extends Thread{
private volatile Counter counter ;
public Thread1(Counter counter){
this.counter = counter;
}
@Override
public void run(){
//synchronized (counter) {
//System.out.println(counter.value+=10);
//}
System.out.println(this.counter.increase());
}
}
还有一个
package icrement;public class Counter { protected long value = 0; public long getValue() {
return value;
}
public long increase(){
//synchronized (this) {
this.value += 10;
return value;
//}
}
}package icrement;public class Thread1 extends Thread{
private volatile Counter counter ;
public Thread1(Counter counter){
this.counter = counter;
}
@Override
public void run(){
synchronized (counter) {
//System.out.println(counter.value+=10);
System.out.println(this.counter.increase());
}
}
}
就是把线程同步块放到run里面和不放到里面的区别
package icrement;public class Counter { protected long value = 0; public long getValue() {
return value;
}
public long increase(){
synchronized (this) {
this.value += 10;
return value;
}
}
}
package icrement;public class Thread1 extends Thread{
private volatile Counter counter ;
public Thread1(Counter counter){
this.counter = counter;
}
@Override
public void run(){
//synchronized (counter) {
//System.out.println(counter.value+=10);
//}
System.out.println(this.counter.increase());
}
}
还有一个
package icrement;public class Counter { protected long value = 0; public long getValue() {
return value;
}
public long increase(){
//synchronized (this) {
this.value += 10;
return value;
//}
}
}package icrement;public class Thread1 extends Thread{
private volatile Counter counter ;
public Thread1(Counter counter){
this.counter = counter;
}
@Override
public void run(){
synchronized (counter) {
//System.out.println(counter.value+=10);
System.out.println(this.counter.increase());
}
}
}
就是把线程同步块放到run里面和不放到里面的区别
第一个更好,因为它遵循了尽量减少锁定对象时间的原则。
第二个要一直等到println()结束才会释放锁,而第一个加法执行完就释放锁了