public class ThreadTest1
{
private int j;
public static void main(String args[])
{
ThreadTest1 tt=new ThreadTest1();
Inc inc=tt.new Inc();
Dec dec=tt.new Dec();
for(int i=0;i<2;i++)
{
Thread t= new Thread(inc);
t.start();
t=new Thread(dec);
t.start();
}
}
private synchronized void inc()
{
j++;
System.out.println(Thread.currentThread.getName()+"-inc:"+j);
}
private synchronized void dec()
{
j--;
System.out.println(Thread.currentThread.getName()+"-dec"+j);
}
class Inc implements Runnable{
public void run()
{
for(int i=0;i<100;i++)
{
inc();
}
}
}
Class Dec implements Runnable{
public void run()
{
for(int i=0;i<100;i++)
{
dec();
}
}
}
}
Java线程同步示例
本文提供了一个使用Java实现的简单线程同步示例。该示例通过两个内部类Inc和Dec实现对共享变量j的增加和减少操作,并利用synchronized关键字确保线程安全。在main方法中创建并启动了多个线程来执行这些操作。
1439

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



