大家看下代码:package com.thread;class Test {
int value = 30; public synchronized int getValue() {
return value;
} public Test() {
T t1 = new T("t1");
T t2 = new T("t2");
t1.start();
t2.start();
} public synchronized void increase() // Test的生产方法
{
value++;
if (value > 30)
System.out.println("increase!!!");
notify();
} public synchronized void decrease() // Test的消费方法
{
try {
value -= 8;
System.out.println("decrease!!!");
if (value <= 0)
wait();
} catch (Exception e) {
e.printStackTrace();
}
} class T extends Thread {
public void run() {
while (true) {
dos();
}
} public T(String n) {
this.setName(n);
} public synchronized void dos() {
} public static void main(String argv[]) {
Test t1 = new Test(); }}大家看下代码
我觉得红字部分的synchronized 没有需要的必要,因为他在这里起不到同步作用
因为
public Test() {
T t1 = new T("t1");
T t2 = new T("t2");
t1.start();
t2.start();
}启动了2个线程 t1,t2 是2个互相 独立的实列,当然其方法dos()也是互相不影响的
不知道我这样分析对不对?
int value = 30; public synchronized int getValue() {
return value;
} public Test() {
T t1 = new T("t1");
T t2 = new T("t2");
t1.start();
t2.start();
} public synchronized void increase() // Test的生产方法
{
value++;
if (value > 30)
System.out.println("increase!!!");
notify();
} public synchronized void decrease() // Test的消费方法
{
try {
value -= 8;
System.out.println("decrease!!!");
if (value <= 0)
wait();
} catch (Exception e) {
e.printStackTrace();
}
} class T extends Thread {
public void run() {
while (true) {
dos();
}
} public T(String n) {
this.setName(n);
} public synchronized void dos() {
} public static void main(String argv[]) {
Test t1 = new Test(); }}大家看下代码
我觉得红字部分的synchronized 没有需要的必要,因为他在这里起不到同步作用
因为
public Test() {
T t1 = new T("t1");
T t2 = new T("t2");
t1.start();
t2.start();
}启动了2个线程 t1,t2 是2个互相 独立的实列,当然其方法dos()也是互相不影响的
不知道我这样分析对不对?
但是你不能保证所有的程序都这样用。万一有人这样写呢:
public Test() {
T t1 = new T("t1");
Thread t2 = new Thread(t1);
Thread t3 = new Thread(t1);
t2.start();
t3.start();
}
你能说synchronized没用么?
String str="t";
T t1 = new T(str);
T t2 = new T(str);
t1.start();
t2.start();
}
这样的话
synchronized就有用了
冲突的话,至少要有共享的对象参数才冲突
没共享的话
就是2个独立线程
比如在Test类中定义一个ArrayList list = new ArrayList();的全局变量
dos方法中如果{
list.add("s");
}
因为ArrayList不是线程安全的,所以不能有两个线程同时调用dos方法,所以得加上synchronized