1、(JDK1.8)线程A打印a,线程B打印l,线程C打印i,三个线程交替打印,各打印102次,alialiali……
package ali;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author tianp
**/
public class PrintAli {
//总数
public static volatile int i = 1;
//0-a 1-l 2-i
public static volatile int a = 0;
public static void main(String[] args) {
print();
}
public static void print() {
new Thread(new Runnable() {
@Override
public void run() {
AtomicInteger ai = new AtomicInteger(0);
while (i < 306) {
if (a == 0) {
System.out.println("a");
i++;
a = 1;
ai.incrementAndGet();
}
}
System.out.println(Thread.currentThread().getName() + "print [a] nums is:" + ai.get());
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
AtomicInteger ai = new AtomicInteger(0);
while (i <= 306) {
if (a == 1) {
System.out.println("l");
i++;
a = 2;
ai.incrementAndGet();
}
}
System.out.println(Thread.currentThread().getName() + "print [l] nums is:" + ai.get());
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
AtomicInteger ai = new AtomicInteger(0);
while (i <= 306) {
if (a == 2) {
System.out.println("i");
i++;
a = 0;
ai.incrementAndGet();
}
}
System.out.println(Thread.currentThread().getName() + "print [i] nums is:" + ai.get());
}
}).start();
}
}
2、小b有一个计数器,其计数规则如下:
-计数从1开始,每过1秒数字+1
-第一次计数周期上限值为5,下一次计数周期上限值为上一次计数周期的两倍
-每次计数到上限值,触发计数重置,即下一个计数重新从1开始
以下是前20秒计数器上显示的数字举例:
1 2 3 4 5 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5
请实现一个方法,输入第n秒,返回计数器上这个时刻的数字
举例1:
输入:1
输出:1
举例2:
输入:15
输出:10
package ali;
/**
* @author tianp
**/
public class Timer {
public static void main(String[] args) {
System.out.println(getNum(20));
}
/**
* 1 1
* 15 10
* 20 5
*
* @param a 秒
*/
public static int getNum(int a) {
if (a <= 5) {
return a;
}
int max = 5;
int now = 0;
for (int i = 1; i <= a; i++) {
now++;
if (i % max == 0 && i!=a) {
max = i + max * 2;
now = 0;
}
}
return now;
}
}
网友评论