package com.hi.test;
public class Tools {
// 如果数据存在 共享的 ,那么为了保证数据的完全性, 需要使用同步
// 如果数据不存在的 共享的问题,那么可以使用 异步, 使用并发执行
public static ThreadLocal<String> t1 = new ThreadLocal<String>();
public static ThreadLocal<Integer> t = new ThreadLocal<Integer>();
public static int total = 1;
public static Object lock = new Object();
public static void main(String[] args) {
new ThreadA(lock).start();
new ThreadB(lock).start();
new ThreadSyncA().start();
new ThreadSyncB().start();
synchronized (lock)
{
for(int i=0;i<100;i++)
{
t1.set("Main =" + (i+1));
System.out.println("Value=" + Tools.t1.get() + " total=" + total);
t.set(1);
int val = Integer.parseInt("" +Tools.t.get());
total += val;
try
{
Thread.sleep(60);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
===== ThreadA class ①
class ThreadA extends Thread{
private Object lock;
public ThreadA(Object lock)
{
this.lock = lock;
}
@Override
public void run()
{
synchronized (lock)
{
for(int i=0;i<100;i++)
{
Tools.t1.set("ThreadA=" + (i+1));
System.out.println("Value=" + Tools.t1.get() + " total=" + Tools.total);
Tools.t.set(1);
int val = Integer.parseInt(""+Tools.t.get());
Tools.total += val;
try
{
Thread.sleep(60);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
===== ThreadA class ②
class ThreadB extends Thread{
private Object lock;
public ThreadB(Object lock)
{
this.lock = lock;
}
@Override
public synchronized void run()
{
synchronized (lock)
{
for(int i=0;i<100;i++)
{
Tools.t1.set("ThreadB=" + (i+1));
System.out.println("Value=" + Tools.t1.get() + " total=" + Tools.total);
Tools.t.set(1);
int val = Integer.parseInt(""+Tools.t.get());
Tools.total += val;
try
{
Thread.sleep(60);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
====ThreadSyncA ③
class ThreadSyncA extends Thread{
@Override
public void run()
{
int total = 0;
for(int i=0;i<100;i++)
{
System.out.println("begin Sync Method ThreadName =>" + Thread.currentThread().getName());
total += 1;
System.out.println("after Sync Method ThreadName =>" + Thread.currentThread().getName());
}
System.out.println("ThreadName="+ Thread.currentThread().getName()+" total=" + total);
}
}
==== ThreadSync ④
class ThreadSyncB extends Thread{
@Override
public void run()
{
int total = 0;
for(int i=0;i<100;i++)
{
System.out.println("begin Sync Method ThreadName =>" + Thread.currentThread().getName());
total += 1;
System.out.println("after Sync Method ThreadName =>" + Thread.currentThread().getName());
}
System.out.println("ThreadName="+ Thread.currentThread().getName() +" total=" + total);
}
}