首页 > 代码库 > 【Java】多线程冲突解决——同步锁
【Java】多线程冲突解决——同步锁
import java.lang.Thread.State;
import org.omg.CORBA.PUBLIC_MEMBER;
public class ThreadTest {
public static void main(String[] args) throws Exception{
MyRunnable m1=new MyRunnable();
Thread t1=new Thread(m1);
Thread t2=new Thread(m1);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(MyRunnable.num);
}
}
class MyRunnable implements Runnable
{
public static int num=0;
public synchronized void add()
{
for(int i=0;i<100;++i)
{
num++;
}
}
@Override
public void run() {
add();
}
}
import java.lang.Thread.State;
import org.omg.CORBA.PUBLIC_MEMBER;
public class ThreadTest {
public static void main(String[] args) throws Exception{
MyRunnable m1=new MyRunnable();
MyRunnable m2=new MyRunnable();
Thread t1=new Thread(m1);
Thread t2=new Thread(m2);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(MyRunnable.num);
}
}
class MyRunnable implements Runnable
{
public static int num=0;
public synchronized static void add()
{
for(int i=0;i<100;++i)
{
num++;
}
}
@Override
public void run() {
add();
}
}
结果:200
public Object lock=new Object();
}
import java.lang.Thread.State;
import org.omg.CORBA.PUBLIC_MEMBER;
public class ThreadTest {
public static void main(String[] args) throws Exception{
MyRunnable m1=new MyRunnable();
Thread t1=new Thread(m1);
Thread t2=new Thread(m1);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(MyRunnable.num);
}
}
class MyRunnable implements Runnable
{
public static int num=0;
public Object lock=new Object();
public void add()
{
synchronized (lock) {
for(int i=0;i<100000;++i)
{
num++;
}
}
}
@Override
public void run() {
add();
}
}
结果:200000
import java.lang.Thread.State;
import org.omg.CORBA.PUBLIC_MEMBER;
public class ThreadTest {
public static void main(String[] args) throws Exception{
MyRunnable m1=new MyRunnable();
MyRunnable m2=new MyRunnable();
Thread t1=new Thread(m1);
Thread t2=new Thread(m2);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(MyRunnable.num);
}
}
class MyRunnable implements Runnable
{
public static int num=0;
public Object lock=new Object();
public void add()
{
synchronized (lock) {
for(int i=0;i<100000;++i)
{
num++;
}
}
}
@Override
public void run() {
add();
}
}
多调试几次:结果是随机的,循环次数越大结果越随机。比如,上面for循环中如果是i<100,那么可能结果总是200,这看起来是对的,没错。原因是循环次数太少,两线程对结果影响不大。当把数字调大,如100000时,结果就很随机了,有可能是103453,112378。。。。。。。
【Java】多线程冲突解决——同步锁