如果每個線程執行的代碼相同,可以使用同一個runnable對象,這個Runnable對象中有那個共享數據
比如賣票程序
每個線程訪問的數據不同,將這個共享數據封在對象中,把這個對象
public class TheardTestController {
public static void main(String[] args) {
//賣票
Sale sale=new Sale();
new Thread(sale).start();
new Thread(sale).start();
//每個線程訪問的數據不同 共享變量j 啓動四個線程 兩個操作j++ 兩個操作j--
//思路是定義兩個內部類實現runnable接口 共享外部類的成員變量
final Calculate c=new Calculate();//c對象爲什麼要用final修飾? 匿名內部類調用外部類的成員,外部類成員是以參數形式傳入的
//在匿名類中需要傳遞進來final關鍵字,java希望的是保證內部實現和外在表現的一致性
//如果不將c設爲final,就不會使得start()函數的局部變量和局部類內建立的拷貝保持一致
for(int i=0;i<2;i++){
new Thread(new Runnable() {
@Override
public void run() {
while(true){
c.add();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true){
c.reduce();
}
}
}).start();
}
}
}
class Calculate{
private int j=0;
public void add(){
j++;
System.out.println(Thread.currentThread().getName()+"add j="+j);
}
public void reduce(){
j--;
System.out.println(Thread.currentThread().getName()+"reduce j="+j);
}
}
class Sale implements Runnable{
private int count=100;
@Override
public void run() {
while(count>0){
count--;
System.out.println(Thread.currentThread().getName()+" count :"+count);
}
}
}