用java编程实现。谢谢
线程同步有两种基本方法:
(1)synchronized (1)synchronized
(2)wait,notify,notifyAll
现在分别采用这两种方法来解答这道题目
package com.thread;
public class TestThread {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PrintTask print......<br/><strong>答案就在这里:</strong><a target='_blank' rel='nofollow' href='http://blog.csdn.net/hanruikai/article/details/7506260'>有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABCABC</a><br/>----------------------Hi,地球人,我是问答机器人小S,上面的内容就是我狂拽酷炫叼炸天的答案,除了赞同,你还有别的选择吗?
synchronized ABC(String str){
System.out.println(str);
}
这是按顺序打印10个ABC
package com.multithread.wait;
public class MyThreadPrinter2 implements Runnable {
private String name;
private Object prev;
private Object self;
private MyThreadPrinter2(String name, Object prev, Object self) {
this.name = name;
this.prev = prev;
this.self = self;
}
@Override
public void run() {
int count = 10;
while (count > 0) {
synchronized (prev) {
synchronized (self) {
System.out.print(name);
count--;
self.notify();
}
try {
prev.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws Exception {
Object a = new Object();
Object b = new Object();
Object c = new Object();
MyThreadPrinter2 pa = new MyThreadPrinter2("A", c, a);
MyThreadPrinter2 pb = new MyThreadPrinter2("B", a, b);
MyThreadPrinter2 pc = new MyThreadPrinter2("C", b, c);
new Thread(pa).start();
Thread.sleep(100); //确保按顺序A、B、C执行
new Thread(pb).start();
Thread.sleep(100);
new Thread(pc).start();
Thread.sleep(100);
}
}
http://blog.csdn.net/havedream_one/article/details/46761487
package demo;__*
public class Demo4
{
static boolean isThreadA = true;
static boolean isThreadB = false;
static boolean isThreadC = false;
public static void main(String[] args)
{
final Demo4 print = new Demo4();//同步锁
Thread t1 = new Thread(new Runnable(){
public void run(){
synchronized (print){
for(int i=0;i<10; i++){
while(!isThreadA){
try{
print.wait();
}
catch (InterruptedException e){
e.printStackTrace();
}
}
System.out.println("A");
isThreadA = false;
isThreadB = true;
isThreadC = false;
print.notifyAll();
}
}
}
});
Thread t2 = new Thread(new Runnable(){
public void run(){
synchronized (print){
for(int i=0;i<10; i++){
while(!isThreadB){
try{
print.wait();
}
catch (InterruptedException e){
e.printStackTrace();
}
}
System.out.println("B");
isThreadA = false;
isThreadB = false;
isThreadC = true;
print.notifyAll();
}
}
}
});
Thread t3 = new Thread(new Runnable(){
public void run(){
synchronized (print){
for(int i=0;i<10; i++){
while(!isThreadC){
try{
print.wait();
}
catch (InterruptedException e){
e.printStackTrace();
}
}
System.out.println("C");
isThreadA = true;
isThreadB = false;
isThreadC = false;
print.notifyAll();
}
}
}
});
t1.start();
t2.start();
t3.start();
}
}