67,513
社区成员
发帖
与我相关
我的任务
分享
class MyThreadTest
{
public static void main(String[] args){
ThreadTest tt = new ThreadTest();
new Thread(tt).start();
new Thread(tt).start();
//new Thread(tt).start();
//new Thread(tt).start();
}
}
class ThreadTest implements Runnable
{
int i = 100;
Object o = new Object();
public void run(){
while(true){
synchronized(o){
try{
Thread.sleep(10);
}catch(Exception e){
e.printStackTrace();
}
synchronized(this){
if(i>0){
System.out.println("同步块~~"+Thread.currentThread().getName()+" "+i);
i--;
}
}
}
test();
}
}
public synchronized void test(){
synchronized(o){
if(i>0){
try{
Thread.sleep(10);
System.out.println("同步方法~~"+Thread.currentThread().getName()+" "+i);
i--;
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
class MyThreadTest
{
public static void main(String[] args){
ThreadTest tt = new ThreadTest();
new Thread(tt).start();
try{
Thread.sleep(1);
}catch(Exception e){
e.printStackTrace();
}
tt.b = true;
new Thread(tt).start();
//new Thread(tt).start();
//new Thread(tt).start();
}
}
class ThreadTest implements Runnable
{
int i = 100;
boolean b = false;
Object o = new Object();
public void run(){
if(b==true){
test();
}else{
while(true){
synchronized(o){
try{
Thread.sleep(10);
}catch(Exception e){
e.printStackTrace();
}
synchronized(this){
if(i>0){
System.out.println("同步块~~"+Thread.currentThread().getName()+" "+i);
i--;
}
}
}
}
}
}
public synchronized void test(){
synchronized(o){
if(i>0){
try{
Thread.sleep(10);
System.out.println("同步方法~~"+Thread.currentThread().getName()+" "+i);
i--;
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}