线程之间的数据共享问题可以分为两类,一类是执行代码一直的的线程共享线程共享,另一类是执行代码不一致的线程共享问题。接下来分别进行总结。
一、执行代码一致的线程共享问题
如果每个线程执行的代码执行的代码相同,那么可以使用同一个runnable对象,这个runnable里面的数据共享。例如下面线程,启动五个线程,共享一个数据对j的操作。
public class Test {
static int j = 0;
public static void main(String[] args) {
Runnbale1 runnbale1 = new Runnbale1();
new Thread(runnbale1).start();
new Thread(runnbale1).start();
new Thread(runnbale1).start();
new Thread(runnbale1).start();
new Thread(runnbale1).start();
}
private static class Runnbale1 implements Runnable{
@Override
public void run() {
j++;
System.out.println(Thread.currentThread().getName()+"---"+j);
}
}
}
打印出如下代码:
二、执行代码不一致的线程共享问题
如果每个线程执行的代码的代码不同,这时候需两个Runnable来实现。方法一:内部类方法,将共享数据写在内部类中,提供每个线程不同的方法(记得加锁),然后创建实例,作为参数传递给每个Runnable构造方法,通过构造方法传递的对象,进行数据数据共享和不同方法的调用;方法二:外部类方法,将共享数据提供在外部类的成员变量中,并且提供外部类的不用线程的方法(记得加锁),然后再Runnable中调用外部类的方法或者变量。
1、内部类法
public class Test2 {
public static void main(String[] args) {
Data data = new Data();
Runnbale1 runnbale1 = new Runnbale1(data);
Runnbale2 runnbale2 = new Runnbale2(data);
new Thread(runnbale1).start();
new Thread(runnbale2).start();
}
private static class Runnbale1 implements Runnable {
private Data data;
public Runnbale1(Data data) {
this.data = data;
}
@Override
public void run() {
int plus = data.plus();
System.out.println(Thread.currentThread().getName() + "---" + plus);
}
}
private static class Runnbale2 implements Runnable {
private Data data;
public Runnbale2(Data data) {
this.data = data;
}
@Override
public void run() {
int reduce = data.reduce();
System.out.println(Thread.currentThread().getName() + "---" + reduce);
}
}
/**
* 共享数据内部类方式:注意加锁
*/
private static class Data {
private int i = 50;
public synchronized int plus(){
return i++;
}
public synchronized int reduce(){
return i--;
}
}
}
打印结果如下:
2、外部类法
public class Test3 {
static int j = 0;
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
new Thread(new Add()).start();
new Thread(new Reduce()).start();
}
}
/**
* 共享数据内部类方式
*/
/*****同步******/
public static synchronized void add(){
j++;
System.out.println("add:"+j);
}
/*****同步******/
public static synchronized void reduce(){
j--;
System.out.println("reduce:"+j);
}
static class Add implements Runnable{
@Override
public void run() {
add();
}
}
static class Reduce implements Runnable{
@Override
public void run() {
reduce();
}
}
}
打印结果如下:
public class Test3 {
static int j = 0;
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
new Thread(new Add()).start();
new Thread(new Reduce()).start();
}
}
/**
* 共享数据内部类方式
*/
/*****同步******/
public static synchronized void add(){
j++;
System.out.println("add:"+j);
}
/*****同步******/
public static synchronized void reduce(){
j--;
System.out.println("reduce:"+j);
}
static class Add implements Runnable{
@Override
public void run() {
add();
}
}
static class Reduce implements Runnable{
@Override
public void run() {
reduce();
}
}
}
打印结果如下:
总结完毕!
版权声明:本文为yoonerloop原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。