public class TestThread {
public static void main( String[] args ) {
TestMath1 tm = new TestMath1();
new Thread ( tm , "TestMath1" ).start();
new Thread ( tm , "TestMath2" ).start();
// TestMath2 tm2 = new TestMath2();
// new Thread ( tm2 , "TestMath2" ).start();
}
}
class TestMath1 implements Runnable {
public void run() {
new Maths().execute( this );
}
}
class TestMath2 implements Runnable {
public void run() {
new Maths().execute( this );
}
}
class Maths {
/*
static Object o = new Object();
public void execute() {
synchronized( o ) {//同步锁,用于锁住当前类实例,知道执行完毕解锁
int i = 0;
while ( i < 20 ) {
System.out.println( Thread.currentThread().getName()+":"+ i );
i++;
}
}
}
public synchronized void execute() {
int i = 0;
while ( i < 20 ) {
System.out.println( Thread.currentThread().getName()+":"+ i );
i++;
}
}
public void execute() {
synchronized( this ) {
int i = 0;
while ( i < 20 ) {
System.out.println( Thread.currentThread().getName()+":"+ i );
i++;
}
}
}*/
public void execute( Object o ) {
synchronized( o ) {
int i = 0;
while ( i < 20 ) {
System.out.println( Thread.currentThread().getName()+":"+ i );
i++;
}
}
}
}
本文通过一个Java多线程示例展示了如何使用synchronized关键字实现线程间的同步操作,确保共享资源的安全访问。两个线程分别通过TestMath1和TestMath2类实例化并启动,它们共享同一个Maths类的实例,该类包含了一个同步方法execute来控制对共享变量的访问。
&spm=1001.2101.3001.5002&articleId=1751519&d=1&t=3&u=6518ce984ad74f34b8b8d4f0ac3af052)
494

被折叠的 条评论
为什么被折叠?



