4个线程问题
- 提问者网友:我的未来我做主
- 2021-05-08 15:22
注:因为这4个线程共享J,所以线程类要写到内部类中。
- 五星知识达人网友:廢物販賣機
- 2021-05-08 16:43
public class TestThreads
{
private int j=1;
//加线程
private
class Inc implements Runnable
{
public void run()
{
for(int i = 0;i <
10;i++)
{
inc();
}
}
}
//减线程
private
class Dec implements Runnable
{
public void run()
{
for(int i = 0;i <
10;i++)
{
dec();
}
}
}
//加1
private
synchronized void inc()
{
j++;
System.out.println(Thread.currentThread().getName()+"-inc:"+j);
}
//减1
private
synchronized void dec()
{
j--;
System.out.println(Thread.currentThread().getName()+"-dec:"+j);
}
//测试程序
public
static void main(String[] args)
{
TestThreads test = new
TestThreads();
//创建两个线程类
Thread thread = null;
Inc
inc = test.new Inc();
Dec dec = test.new Dec();
//启动4个线程
for(int i = 0;i < 2;i++)
{
thread = new Thread(inc);
thread.start();
thread = new Thread(dec);
thread.start();
}
}
}