package com.shit.thread.thread4;public class A extends Thread
{
public int time;
public A(int time)
{
this.time = time;
}
public void run()
{
a(time);
b(time);
}
public synchronized void a(int time)
{
try
{
this.sleep(time);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("a: " + time);
}
public synchronized void b(int time)
{
try
{
this.sleep(time);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("b: " + time);
}
}
线程a调用a方法,线程b调用b方法,这2个调用相互排斥吗?
怎么写一个测试方法?
public class A implements Runnable
{
public int time;
public A(int time)
{
this.time = time;
}
public void run()
{
a(time);
b(time);
}
public synchronized void a(int time)
{
try
{
Thread.sleep(time);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("a: " + time);
}
public synchronized void b(int time)
{
try
{
Thread.sleep(time);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("b: " + time);
}
public static void main(String[] args) {
A a = new A(1000);
new Thread(a).start();
new Thread(a).start();
}
}
给你修改下,实现Runnable接口。
如果extends Thread就不满足竞争同一个对象的问题。
A a = new A(1000);
A b = new A(2000);
a.start();
b.start();