国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java線程重復執行以及操作共享變量的代碼示例

2019-11-26 14:46:33
字體:
來源:轉載
供稿:網友

1.題目:主線程執行10次,子線程執行10次,此過程重復50次

代碼:

package com.Thread.test;/* * function:主線程執行10次,子線程執行10次, * 此過程重復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;//實現4個線程,兩個線程加1,兩個線程減1public class Demo1 { private static int j=0; private A a = new A(); //構造函數 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); } }  //用于測試的主函數 public static void main(String[] args) {  Demo1 demo = new Demo1(); }}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 定兴县| 定陶县| 海晏县| 淅川县| 十堰市| 余干县| 南京市| 金山区| 太康县| 正阳县| 政和县| 长顺县| 古交市| 江津市| 盐亭县| 沾益县| 大厂| 建水县| 盐城市| 克山县| 武强县| 林芝县| 东平县| 文登市| 松潘县| 宁波市| 临湘市| 普陀区| 蒲江县| 民勤县| 罗源县| 长泰县| 通化市| 西平县| 五原县| 察隅县| 盖州市| 邓州市| 丰城市| 巫山县| 赤壁市|