JAVA双线程 用两个线程交替打印从1到100。 如:线程1 1 线程2 2
2个回答
展开全部
public class Spider {
class Egg implements Runnable {
String name;
public Egg(String name) {
this.name = name;
}
Thread thread;
public void start() {
if (null == thread) {
thread = new Thread(this);
thread.setName(name);
thread.start();
}
}
public synchronized void stop() {
if (null != thread) {
thread.interrupt();
thread = null;
notifyAll();
}
}
public void run() {
Thread me = Thread.currentThread();
while (me == thread) {
if (count > 99) {
stop();
break;
}
try {
Thread.sleep(50);
} catch (Exception e) {}
System.out.println(me.getName() + " " + count++);
}
}
}
int count = 1;
public Spider(int num) {
for (int i = 0; i < num; i++) {
Egg egg = new Egg("线程" + (i + 1));
egg.start();
}
}
public static void main(String[] args) {
new Spider(2);
}
}
展开全部
通过公平锁实现
import java.util.concurrent.locks.ReentrantLock;
public class FairLock implements Runnable {
private static ReentrantLock fairLock = new ReentrantLock(true);
private static int i = 1;
@Override
public void run() {
while(i < 100){
try{
fairLock.lock();
System.out.println(Thread.currentThread().getName()+" " + i++);
}finally{
fairLock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
FairLock r1 = new FairLock();
Thread t1=new Thread(r1,"Thread_t1");
Thread t2=new Thread(r1,"Thread_t2");
t1.start();t2.start();
}
}
import java.util.concurrent.locks.ReentrantLock;
public class FairLock implements Runnable {
private static ReentrantLock fairLock = new ReentrantLock(true);
private static int i = 1;
@Override
public void run() {
while(i < 100){
try{
fairLock.lock();
System.out.println(Thread.currentThread().getName()+" " + i++);
}finally{
fairLock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
FairLock r1 = new FairLock();
Thread t1=new Thread(r1,"Thread_t1");
Thread t2=new Thread(r1,"Thread_t2");
t1.start();t2.start();
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询