package com.zrm.thread;
/**
* 同过实现Runnable接口并实现run方法来创建一个新的线程
*/
public class RunDemo implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName() + "" + "线程执行的第" + i + "次");
}
}
public static void main(String[] args) {
RunDemo runDemo = new RunDemo();
Thread thread = new Thread(runDemo);
thread.start();
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName() + "" + "线程执行的第" + i + "次");
}
}
}
package com.zrm.thread;
/**
* 通过集成Thread类并从写run方法来创建线程
*/
public class ThreadDemo extends Thread {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName() + "线程执行的第" + i + "次");
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
public static void main(String[] args) throws InterruptedException {
ThreadDemo demo = new ThreadDemo();
demo.start();
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName() + "线程执行的第" + i + "次");
// Thread.sleep(1000);
}
}
}
//同步代码块实现
package com.zrm.thread;
public class Ticket implements Runnable {
private Integer NUMBER = 10;
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this) {
if (NUMBER > 0) {
NUMBER--;
System.out.println(Thread.currentThread().getName() + "买到了第" + NUMBER + "张票");
}
}
}
}
public static void main(String[] args) {
Ticket ticket = new Ticket();
Thread thread = new Thread(ticket, "A");
Thread thread2 = new Thread(ticket, "B");
Thread thread3 = new Thread(ticket, "C");
Thread thread4 = new Thread(ticket, "D");
thread.start();
thread2.start();
thread3.start();
thread4.start();
}
}
package com.zrm.thread;
public class SynMethod implements Runnable {
private int NUMBER = 100;
@Override
public void run() {
for (int i = 0; i < 100; i++) {
this.sale();
}
}
//同步方法实现
public synchronized void sale() {
if (this.NUMBER > 0) {
System.out.println(Thread.currentThread().getName() + "买到了票" + this.NUMBER--);
}
}
public static void main(String[] args) {
Ticket ticket = new Ticket();
Thread thread = new Thread(ticket, "A");
Thread thread2 = new Thread(ticket, "B");
Thread thread3 = new Thread(ticket, "C");
Thread thread4 = new Thread(ticket, "D");
thread.start();
thread2.start();
thread3.start();
thread4.start();
}
}