***一個Thread對象只能開啓一個線程,而一個實現了Runnable接口的對象可以開啓多個線程***
在實際項目開發中,我們往往需要注意數據的敏感性,特別是對於數據極其敏感的行業項目,所以我們需要使用線程同步來解決這些問題!如下面的代碼
public class TestThread implements Runnable {
Timer timer = new Timer();
public static void main(String[] args) {
TestThread t = new TestThread();
Thread tt1 = new Thread(t);
Thread tt2 = new Thread(t);
Thread tt3 = new Thread(t);
tt1.setName("tt1");
tt2.setName("tt2");
tt3.setName("tt3");
tt1.start();
tt2.start();
tt3.start();
}
public void run() {
timer.show(Thread.currentThread().getName());
}
}
class Timer {
private static int i = 0;
public void show(String name) { i++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("這是第" + i + "個Timer,名爲:" + name);
}
}
上面代碼顯示的不是我們希望看到的結果,因爲他們是同時操作的同一個對象,如同購物,你拿十元可以同時購買所有十元以下的商品一樣!
所以必需對其做一定的修改:
public class TestThread implements Runnable {
Timer timer = new Timer();
public static void main(String[] args) {
TestThread t = new TestThread();
Thread tt1 = new Thread(t);
Thread tt2 = new Thread(t);
Thread tt3 = new Thread(t);
tt1.setName("tt1");
tt2.setName("tt2");
tt3.setName("tt3");
tt1.start();
tt2.start();
tt3.start();
}
public void run() {
timer.show(Thread.currentThread().getName());
}
}
class Timer {
private static int i = 0;
public void show(String name) {
synchronized (this) {
i++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("這是第" + i + "個Timer,名爲:" + name);
}
}
}
這樣,鎖定當前使用對象,那麼其他的線程就不能在當前線程使用的同時而使用它了!