代码看不懂,有人帮忙分析一下吗,哭了
通过synchronized方法使两个子线程互斥访问全局变量count,用lock锁的方法用构造临界区使两个子线程互斥访问打印程序,这个怎么修改源代码,lock锁构造临界区??
为什么我去掉临界区和互斥控制后,运行的结果不变
public class ThreadMutex {
public void print(int printer, String content)
{
//临界区
synchronized(this)
{
System.out.println("Start working for [" +printer+"]");
Thread.yield();
System.out.println("===================");
Thread.yield();
System.out.println(content);
Thread.yield();
System.out.println("===================");
Thread.yield();
System.out.println("Work complete for [" +printer+"]\n");
}
}
public static void main(String[] args)
{
//创建线程
ThreadMutex p = new ThreadMutex();
//创建3个线程
for (int i=0; i<3; i++)
//启动线程
new Thread(new Thread1(p)).start();
}
}
class Thread1 implements Runnable
{
private static int counter = 0;
private final int id = counter++;
private ThreadMutex printer;
public Thread1(ThreadMutex printer)
{
this.printer = printer;
}
@Override
//重写run方法
public void run()
{
printer.print(id, "Content of " + id);
}
}
程序2
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadLock {
/**
* @param args
*/
public int count=0;
class mythread1 implements Runnable{
private Lock lock=new ReentrantLock();
public void compute1(){
lock.lock();//加锁
try
{
count=count+5;
System.out.println("线程1---"+count);
}
finally
{
lock.unlock();//解锁
}
}
@Override
public void run() {
// TODO Auto-generated method stub
compute1();
}
}
class mythread2 implements Runnable{
private Lock lock=new ReentrantLock();
public void compute2(){
lock.lock();//加锁
try
{
count=count+112;
System.out.println("线程2---"+count);
}
finally
{
lock.unlock();//解锁
}
}
@Override
public void run() {
// TODO Auto-generated method stub
compute2();
}
}
@SuppressWarnings("deprecation")
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadLock threadlock=new ThreadLock();
mythread1 t1=threadlock.new mythread1();
mythread2 t2=threadlock.new mythread2();
//创建两个子线程
Thread thread1 = new Thread(t1);
Thread thread2 = new Thread(t2);
//启动两个子线程
thread1.start();
thread2.start();
}
}
没明白你的意思,但是你写了两个Runnable类,本身就不会互斥吧