Java線程重複執行以及操作共用變數的程式碼範例_java

來源:互聯網
上載者:User

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(); }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.