Java線程重復(fù)執(zhí)行以及操作共享變量的代碼示例
更新時間:2015年12月08日 15:02:43 投稿:goldensun
這篇文章主要介紹了Java中對線程重復(fù)執(zhí)行以及操作共享變量的代碼示例,來自于Java面試題目的練習(xí)整理,需要的朋友可以參考下
1.題目:主線程執(zhí)行10次,子線程執(zhí)行10次,此過程重復(fù)50次
代碼:
package com.Thread.test; /* * function:主線程執(zhí)行10次,子線程執(zhí)行10次, * 此過程重復(fù)50次 */ public class ThreadProblem { public ThreadProblem() { final Business bus = new Business(); new Thread(new Runnable() { public void run() { for(int j=0;j<50;j++) { bus.sub(j); } } }).start(); for(int j=0;j<50;j++) { bus.main(j); } } class Business { private boolean tag=true; public synchronized void sub(int num) { if(!tag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int i=0;i<10;i++) { System.out.println("sub thread "+i+",loop "+num+"."); } tag=false; notify(); } public synchronized void main(int num) { if(tag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int i=0;i<10;i++) { System.out.println("main thread "+i+",loop "+num+"."); } tag=true; notify(); } } public static void main(String[] args) { ThreadProblem problem = new ThreadProblem(); } }
2.四個線程,共享一個變量j,其中兩個線程對j加1,兩個線程對j減1。
代碼如下:
package com.Thread.test; //實現(xiàn)4個線程,兩個線程加1,兩個線程減1 public class Demo1 { private static int j=0; private A a = new A(); //構(gòu)造函數(shù) public Demo1() { System.out.println("j的初始值為:"+j); for(int i=0;i<2;i++) { new Thread(new Runnable(){ public void run() { for(int k=0;k<5;k++){ a.add1(); } } }).start(); new Thread(new Runnable(){ public void run() { for(int k=0;k<5;k++) { a.delete1(); } } }).start(); } } class A { public synchronized void add1() { j++; System.out.println(Thread.currentThread().getName()+"對j加1,目前j="+Demo1.j); } public synchronized void delete1() { j--; System.out.println(Thread.currentThread().getName()+"對j減1,目前j="+Demo1.j); } } //用于測試的主函數(shù) public static void main(String[] args) { Demo1 demo = new Demo1(); } }
相關(guān)文章
SpringBoot個性化啟動Banner設(shè)置方法解析
這篇文章主要介紹了SpringBoot個性化啟動Banner設(shè)置方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-03-03深入解析Java的Hibernate框架中的一對一關(guān)聯(lián)映射
這篇文章主要介紹了Java的Hibernate框架的一對一關(guān)聯(lián)映射,包括對一對一外聯(lián)映射的講解,需要的朋友可以參考下2016-01-01JSON復(fù)雜數(shù)據(jù)處理之Json樹形結(jié)構(gòu)數(shù)據(jù)轉(zhuǎn)Java對象并存儲到數(shù)據(jù)庫的實現(xiàn)
這篇文章主要介紹了JSON復(fù)雜數(shù)據(jù)處理之Json樹形結(jié)構(gòu)數(shù)據(jù)轉(zhuǎn)Java對象并存儲到數(shù)據(jù)庫的實現(xiàn)的相關(guān)資料,需要的朋友可以參考下2016-03-03Java實現(xiàn)Random隨機數(shù)生成雙色球號碼
使用Random類是Java中用于生成隨機數(shù)的標(biāo)準(zhǔn)類,本文主要介紹了Java實現(xiàn)Random隨機數(shù)生成雙色球號碼,具有一定的參考價值,感興趣的可以了解一下2023-11-11