Java線程反復履行和操作同享變量的代碼示例。本站提示廣大學習愛好者:(Java線程反復履行和操作同享變量的代碼示例)文章只能為提供參考,不一定能成為您想要的結果。以下是Java線程反復履行和操作同享變量的代碼示例正文
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,兩個線程減1
public 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();
}
}