我想用下面的格式打印数字。这应该由两个线程t1,t2来处理。有没有人能帮我增强我写的下面的代码?
First t1 should print 0-4
Then t2 should print 5-9
Then again t1 should print 10-14
Then t2 should print 15-190 1 2 3 4
5 6 7 8 9
10 11 12 13 14
class PrintNumber implements Runnable{
String name;
public void run(){
print();
}
synchronized public void print(){
for(int i=0;i< 5;i++){
System.out.println(i+" -- "+Thread.currentThread());
}
}
public static void main(String[] args){
Runnable r = new PrintNumber();
Thread t1 = new Thread(r,"t1");
Thread t2 = new Thread(r,"t2");
t1.start();
t2.start();
}
}发布于 2017-07-07 16:06:23
您可以使用两个Sempaphores,而不是使用低级wait()和notify()。每个Runnable都有一个等待的Semaphore和一个用来通知下一个的a。
import java.util.concurrent.Semaphore;
class PrintNumber implements Runnable{
static volatile int nextStartIdx;
private Semaphore waitForSemaphore;
private Semaphore next;
public PrintNumber(Semaphore waitFor, Semaphore next) {
this.waitForSemaphore = waitFor;
this.next = next;
}
public void run(){
while (true) {
print();
}
}
public void print() {
try {
waitForSemaphore.acquire();
int start = nextStartIdx;
for(int i=0;i< 5;i++){
System.out.println(String.format("%d -- %s", i + start, Thread.currentThread().getName()));
}
nextStartIdx += 5;
next.release();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args){
Semaphore a = new Semaphore(1);
Semaphore b = new Semaphore(0);
Thread t1 = new Thread(new PrintNumber(a,b),"t1");
Thread t2 = new Thread(new PrintNumber(b,a),"t2");
t1.start();
t2.start();
}
}发布于 2017-07-07 15:45:52
您可以使用等待和通知来实现sczenario的线程间通信。
class PrintNumber implements Runnable {
String name;
Integer count = 0;
@Override
public void run() {
try {
print();
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
synchronized public void print() throws InterruptedException {
while (count < 15) {
for (int i = 0; i < 5; i++) {
count++;
System.out.println(count + " -- " + Thread.currentThread());
}
notifyAll();
wait();
}
}
public static void main(final String[] args) {
final Runnable r = new PrintNumber();
final Thread t1 = new Thread(r, "t1");
final Thread t2 = new Thread(r, "t2");
t1.start();
t2.start();
}
}有关详细信息,请参阅:
https://stackoverflow.com/questions/44964937
复制相似问题