java多線程變數-ag真人国际官网
① java多線程 全局變數
你這個全局變數是static變數嗎?必須是static才是全局的
然後要保證這個調用全局變數的類和那個線程是在同一個進程
然後要考慮執行的順序,保證賦值的線程先執行
② java多線程共享變數
兩個線程同時獲取變數,
獲取之後.第一個線程 操作,然後進入睡眠.
這時,第二個線程,也獲取到了,做--操作.睡眠.
第一個線程醒來列印的是做過2次運算的數據( ,--)所以是0
第二線程也一樣.
這涉及到多線程安全問題.
③ 基礎java題 試編寫一個多線程的程序:啟動4個線程。其中兩個循環10次,每次將某全局變數加1,另兩個循環1
publicclassday18_a{
publicstaticvoidmain(string[]args)throwsinterruptedexception{
recounrec=recoun.getrec();
thread[]枯蘆trr=newthread[4];
for(inti=0;i<4;i ){
trr[i]=newthread(newnumbertest(rec,i),"線程" (i 1) ": ");
}
for(threadthread:trr){
thread.start();
}
for(threadthread:trr)沒純帶{
thread.join();
}
system.out.println("所有線程結束褲虧查看結果:" rec.getcount());
}
}
{
privaterecounre;
privateintn;
numbertest(recounr,inti){
this.re=r;
this.n=i;
}
publicvoidrun(){
for(inti=0;i<10;i ){
re.method(n);
}
}
}
classrecoun{
privateintcount=0;
privaterecoun(){
}
privatestaticfinalrecounrec=newrecoun();
publicstaticrecoungetrec(){
returnrec;
}
publicsynchronizedvoidmethod(inti){
if(i%2==0){
system.out.println(thread.currentthread().getname() (count ));
}else{
system.out.println(thread.currentthread().getname() (count--));
}
}
publicsynchronizedintgetcount(){
returncount;
}
}
④ java兩個線程操作一個變數,為什麼變數的值會不一樣呢
如樓下所說,線程同步的問題。
除了了使用synchronized。
還可以使用原子類型,例如atomicinteger,參見
http://dlc.sun.com.edgesuite.net/jdk/jdk-api-localizations/jdk-api-zh-cn/publish/1.6.0/html/zh_cn/api/index.html
⑤ java 多線程 同時操作一個變數 高分懸賞
arraylist不是線程安全的野遲 所以 synchronized 必須有 這一點是關鍵,其他的都是浮雲。還有 兩個線程sleep一會更好 否則 這個猛喊跟死循環一樣了 機器受不了啊!。
public class test {
public static list
public static void main(string[] args) {
mythreadclass1 thread1 = new mythreadclass1();
mythreadclass2 thread2 = new mythreadclass2();
thread t1 = new thread(thread1);
thread t2 = new thread(thread2);
t1.start();
t2.start();
}
}
class mythreadclass1 implements runnable {
public void run() {
while (true) {//枝脊野 這就不要寫1 ==1 了
synchronized (test.class) {
system.out.println("add!!!!");
test.list.add("123");
}
try {
thread.sleep(100);
} catch (interruptedexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
}
}
class mythreadclass2 implements runnable {
public void run() {
while (true) {
synchronized (test.class) {
iterator it = test.list.iterator();
// 循環里remove會出沖突異常的
list list2 = new arraylist();
while (it.hasnext()) {
object obj = it.next();
system.out.println("remove:" obj);
list2.add(obj);
}
// you can do anything with list2
// avoid java.util.
test.list.clear();
}
try {
thread.sleep(100);
} catch (interruptedexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
}
}
⑥ java多線程有幾種實現方法,都是什麼同步有幾種實現方法,都是什麼
java中多線程的實現方法有兩種:1.直接繼承thread類;2.實現runnable介面;同步的實現方法有五種:1.同步方法;2.同步代碼塊;3.使用特殊域變數(volatile)實現線程同步;4.使用重入鎖實現線程同步;5.使用局部變數實現線程同步
。
其中多線程實現過程中需注意重寫或者覆蓋run()方法,而對於同步的實現方法中使用較常使用的是利用synchronized編寫同步方法和代碼塊。