1.手写单例模式
public class Single {
private volatile static Single singleCase;
private Single() {}
public static Single getSingleCase(){
if(singleCase == null){
synchronized (Single.class){
if(singleCase == null){
singleCase = new Single();
}
}
}
return singleCase;
}
}
2.多线程实现输出1~100;
(1)三个线程依次轮流输出
public class Print200 {
public static volatile int flag = 0;
public static int num = 0;
public static void main(String[] args){
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
Thread3 t3 = new Thread3();
t1.start();
t2.start();
t3.start();
}
static class Thread1 extends Thread{
@Override
public void run() {
while (num <= 100){
if(flag == 0){
System.out.println(num);
num++;
flag = 1;
}
}
}
}
static class Thread2 extends Thread{
@Override
public void run() {
while (num <= 100){
if(flag == 1){
System.out.println(num);
num++;
flag = 2;
}
}
}
}
static class Thread3 extends Thread{
@Override
public void run() {
while (num <= 100){
if(flag == 2){
System.out.println(num);
num++;
flag = 0;
}
}
}
}
}
(2)通过让Thread重新run方法时引用自定义方法,其中使用了Lock锁。
public class Print2001 {
//private int state = 0;
private int num = 0;
private Lock lock = new ReentrantLock();
private Print2001(){
}
private void sou(int state, String name){
if (num >= 100) return;
while (num < 100){
if(num % 3 == state){
lock.lock();
num++;
System.out.println(name + num);
lock.unlock();
}
}
}
public static void main(String[] args) {
Print2001 p = new Print2001();
new Thread(new Runnable() {
@Override
public void run() {
p.sou(0, "A");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
p.sou(1, "B");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
p.sou(2, "C");
}
}).start();
}
}
(3)乱序输出1-100,使用原子类
public class Print2002 {
private static AtomicInteger atomicInteger = new AtomicInteger(0);
public static void main(String[] args) {
Thread4 t1 = new Thread4();
Thread4 t2 = new Thread4();
Thread4 t3 = new Thread4();
t1.start();
t2.start();
t3.start();
}
static class Thread4 extends Thread{
@Override
public void run() {
while (atomicInteger.get() <= 100) {
System.out.println(atomicInteger);
atomicInteger.incrementAndGet();
}
}
}
}
对上述进行修改:
实现顺序输出,还是使用原子类
public class Print2002 {
private static AtomicInteger atomicInteger = new AtomicInteger(0);
public static void main(String[] args) {
Thread4 t1 = new Thread4(0);
Thread4 t2 = new Thread4(1);
Thread4 t3 = new Thread4(2);
t1.start();
t2.start();
t3.start();
}
static class Thread4 extends Thread{
int state;
public Thread4(int state){
super();
this.state = state;
}
@Override
public void run() {
while (atomicInteger.get() <= 100) {
if(atomicInteger.get() % 3 == state){
System.out.println(atomicInteger);
atomicInteger.incrementAndGet();
}
}
}
}
}