JAVA创建两个线程,一个实现输出1,一个实现输出2.写出程序,实现输出结果为12121212.谢谢~~
3个回答
展开全部
import javax.xml.stream.events.StartDocument;
public class ThreadTest {
public static void main(String[] args) {
Handle2 handle2 = new Handle2();
Thread thread2 = new Thread(handle2);
Handle1 handle1 = new Handle1();
Thread thread1 = new Thread(handle1);
thread1.start();
thread2.start();
}
}
class Handle1 implements Runnable{
public void run() {
for (int i = 0; i < 4; i++) {
try {
Thread.sleep(99);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("1");
}
}
}
class Handle2 implements Runnable{
public void run() {
for (int i = 0; i < 4; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("2");
}
}
}
很不专业!我初学者
public class ThreadTest {
public static void main(String[] args) {
Handle2 handle2 = new Handle2();
Thread thread2 = new Thread(handle2);
Handle1 handle1 = new Handle1();
Thread thread1 = new Thread(handle1);
thread1.start();
thread2.start();
}
}
class Handle1 implements Runnable{
public void run() {
for (int i = 0; i < 4; i++) {
try {
Thread.sleep(99);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("1");
}
}
}
class Handle2 implements Runnable{
public void run() {
for (int i = 0; i < 4; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("2");
}
}
}
很不专业!我初学者
更多追问追答
追问
运行正确!真厉害,不过,不明白为什么要sleep(99)和sleep(100)呢。换成其他的数可以吗?多谢~
追答
起控制作用的,让12121212有序打印
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
循环输出吗?
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
你要的是这个效果不??
public class A {
public static void main(String[] args) {
int a = 0;
Thread t1 = new Thread() {
@Override
public void run() {
while (true) {
print("1");
this.yield();
}
}
};
Thread t2 = new Thread() {
@Override
public void run() {
while (true) {
this.yield();
print("2");
}
}
};
t1.start();
t2.start();
}
public static synchronized void print(String s) {
System.out.println(s);
}
}
public class A {
public static void main(String[] args) {
int a = 0;
Thread t1 = new Thread() {
@Override
public void run() {
while (true) {
print("1");
this.yield();
}
}
};
Thread t2 = new Thread() {
@Override
public void run() {
while (true) {
this.yield();
print("2");
}
}
};
t1.start();
t2.start();
}
public static synchronized void print(String s) {
System.out.println(s);
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询