class ThreadText implements Runnable{
Num num;
@Override
public void run() {
while(true){
synchronized (num) {
System.out.println(Thread.currentThread().getName()+":"+num.i++);
}
}
}
}
class ThreadText2 implements Runnable{
Num num;
@Override
public void run() {
while(true){
synchronized (num) {
System.out.println(Thread.currentThread().getName()+":"+num.i--);
}
}
}
}
public class Demo6 {
public static void main(String[] args) {
ThreadText T0=new ThreadText();
ThreadText2 T=new ThreadText2();
Thread T1=new Thread(T0);
Thread T2=new Thread(T0);
Thread T3=new Thread(T);
Thread T4=new Thread(T);
T1.start();
T2.start();
T3.start();
T4.start();
}
}
class Num{
int i;
}
3 个解决方案
#1
Num是个对象,使用对象的方法需要new出一个实例才行,或者把Num中的i变为静态变量
package Demo;
class ThreadText implements Runnable{
public void run() {
while(true){
synchronized (Num.class) {
System.out.println(Thread.currentThread().getName()+":"+Num.i++);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class ThreadText2 implements Runnable{
public void run() {
while(true){
synchronized (Num.class) {
System.out.println(Thread.currentThread().getName()+":"+Num.i--);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Demo6 {
public static void main(String[] args) {
ThreadText T0=new ThreadText();
ThreadText2 T=new ThreadText2();
Thread T1=new Thread(T0);
Thread T2=new Thread(T0);
Thread T3=new Thread(T);
Thread T4=new Thread(T);
T1.start();
T2.start();
T3.start();
T4.start();
}
}
class Num{
public static int i;
}
#2
多谢 明白了
#3
谢谢 明白了
#1
Num是个对象,使用对象的方法需要new出一个实例才行,或者把Num中的i变为静态变量
package Demo;
class ThreadText implements Runnable{
public void run() {
while(true){
synchronized (Num.class) {
System.out.println(Thread.currentThread().getName()+":"+Num.i++);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class ThreadText2 implements Runnable{
public void run() {
while(true){
synchronized (Num.class) {
System.out.println(Thread.currentThread().getName()+":"+Num.i--);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Demo6 {
public static void main(String[] args) {
ThreadText T0=new ThreadText();
ThreadText2 T=new ThreadText2();
Thread T1=new Thread(T0);
Thread T2=new Thread(T0);
Thread T3=new Thread(T);
Thread T4=new Thread(T);
T1.start();
T2.start();
T3.start();
T4.start();
}
}
class Num{
public static int i;
}
#2
多谢 明白了
#3
谢谢 明白了