日期:2014-05-20  浏览次数:20787 次

JAVA多线程的相关问题
这里面的Synchronizated关键字的作用是什么?
好像有与没,没多大区别啊。

public class TestTh1
{
public static void main(String args[])
{
ThreadT t=new ThreadT();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
Thread t3=new Thread(t);
Thread t4=new Thread(t);
Thread t5=new Thread(t);
Thread t6=new Thread(t);
Thread t7=new Thread(t);
Thread t8=new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();

}
}
class ThreadT implements Runnable
{
private int sum=0;
String str=new String("");
public void run()
{
while(true)
{
synchronized(str)
{if(sum<=10){
}
try{
Thread.sleep(1000);
}catch(InterruptedException w){}
System.out.println(Thread.currentThread().getName()+"now sum is "+sum++);}}
}
}

------解决方案--------------------
1.synchronized的意义
synchronized用于多线程设计,有了synchronized关键字,多线程程序的运行结果将变得可以控制。synchronized关键字用于保护共享数据。
2.synchronized实现同步的机制
synchronized依靠"锁"机制进行多线程同步,"锁"有2种,一种是对象锁,一种是类锁。
3.此下面2种是依靠对象锁锁定,初始化一个对象时,自动有一个对象锁。synchronized {普通方法}依靠对象锁工作,多线程访问ynchronized方法,一旦某个进程抢得锁之后,其他的进程只有排队对待。
synchronized void method{}功能上,等效于
void method{
synchronized(this)
}
}

synchronized {修饰代码块}的作用不仅于此,synchronized void method{}整个函数加上synchronized块,效率并不好。在函数内部,可能我们需要同步的只是小部分共享数据,其他数据,可以自由访问,这时候我们可以用 synchronized(表达式){//语句}更加精确的控制。
4.synchronized {static方法}此代码块等效于
void method{
synchronized(Obl.class)
}
}
使用该类的类对象的锁定去做线程的共享互斥.

5.synchronized {run方法}run方法的锁定.
这个举例比较好说。
public class MyThread implement Runnable{
public void run(){
for(int i=0;i<10;i++){
System.out.println(i+" ");
}
}
}
如果在主程序多线程运行
MyThread t=new MyThread ();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
其结果是混乱不堪的。
如果加了synchronized当前线程取完所有数据后,才会释放锁,所以结果可以预知。4个线程输出总是0,1...9 

你也可以参考这篇文章:
http://hi.baidu.com/yupad/blog/item/e84f3b63dc9c46d4e6113a26.html
------解决方案--------------------
有区别,只是区别还没有体现出来,LZ让线程睡眠一些时间,程序就会显示出区别的
------解决方案--------------------
有和没有 区别很大 有Synchronizated 就跟加了把锁一样,你不解锁 其他线程就没法运行
------解决方案--------------------
你这种用法起不到实际意义。记住锁是为了锁住数据而存在的,如果数据没有并发性就没有必要用锁
------解决方案--------------------
一楼说的挺清楚了的

public class ThreadT implements Runnable {

public int sum=0;

public synchronized void run() {
try {
Thread.sleep(1000);
System.out.println("sum is:" + sum);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadT.class.getName()).log(Level.SEVERE, null, ex);
}
}


public void changeSum()
{
//修改sum的值
this.sum=3;
}


}





public class Test1 {
public static void main(String args[])
{
try {
ThreadT th = new ThreadT();
Thread t1 = new Thread(th);
t1.start();
//让main方法休眠1秒,否则程序运行太快看不到效果
Thread.sleep(1000);

//改变数值

th.changeSum();
} catch (InterruptedException ex) {
Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
}
}