用JAVA写一个多线程程序,如写四个线程,二个对一个变量减一,输出。
2个回答
展开全部
public class Test {
int i=0;//在线程中对这个变量进行加减操作,并输出操作后的值
public static void main(String[] args) {
Test test = new Test();
new AddTest(test).start();
new DecTest(test).start();
}
}
class AddTest extends Thread {
private Test test;
public AddTest(Test t) {
super();
test = t;
}
public void run() {
while (!interrupted()){
test.i++;
System.out.println(test.i);
try {
sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
class DecTest extends Thread {
private Test test;
public DecTest(Test t) {
super();
test = t;
}
public void run() {
while (!interrupted()){
test.i--;
System.out.println(test.i);
try {
sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
int i=0;//在线程中对这个变量进行加减操作,并输出操作后的值
public static void main(String[] args) {
Test test = new Test();
new AddTest(test).start();
new DecTest(test).start();
}
}
class AddTest extends Thread {
private Test test;
public AddTest(Test t) {
super();
test = t;
}
public void run() {
while (!interrupted()){
test.i++;
System.out.println(test.i);
try {
sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
class DecTest extends Thread {
private Test test;
public DecTest(Test t) {
super();
test = t;
}
public void run() {
while (!interrupted()){
test.i--;
System.out.println(test.i);
try {
sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
展开全部
public class Test
{
private int j;
public static void main(String args[]){
Test tt=new Test();
Test1 test1=tt.new Test1();
Test2 test2=tt.new Test2();
for(int i=0;i<2;i++){
Thread t=new Thread(test1);
t.start();
t=new Thread(test2);
t.start();
}
}
private synchronized void test1(){
j++;
System.out.println(Thread.currentThread().getName()+"-test1:"+j);
}private synchronized void test2(){
j--;
System.out.println(Thread.currentThread().getName()+"-test2:"+j);
}
class Test1 implements Runnable{
public void run(){
for(int i=0;i<100;i++){
test1();
}
}
}
class Test2 implements Runnable{
public void run(){
for(int i=0;i<100;i++){
test2();
}
}
}
}
希望能帮到你·
{
private int j;
public static void main(String args[]){
Test tt=new Test();
Test1 test1=tt.new Test1();
Test2 test2=tt.new Test2();
for(int i=0;i<2;i++){
Thread t=new Thread(test1);
t.start();
t=new Thread(test2);
t.start();
}
}
private synchronized void test1(){
j++;
System.out.println(Thread.currentThread().getName()+"-test1:"+j);
}private synchronized void test2(){
j--;
System.out.println(Thread.currentThread().getName()+"-test2:"+j);
}
class Test1 implements Runnable{
public void run(){
for(int i=0;i<100;i++){
test1();
}
}
}
class Test2 implements Runnable{
public void run(){
for(int i=0;i<100;i++){
test2();
}
}
}
}
希望能帮到你·
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询