您的位置:首页 > 编程语言 > Java开发

Java线程重复执行以及操作共享变量的代码示例

2015-12-08 15:02 896 查看

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

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java 线程