package com.taidou;
//继承Thread类
public class TestThread extends Thread{
//重写run方法
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("Thread线程"+i);
}
}
//main线程,主线程
public static void main(String[] args) {
//创建线程对象,调用start方法启动线程
TestThread thread = new TestThread();
thread.start();
//main方法体
for (int i = 0; i < 200; i++) {
System.out.println("main线程"+i);
}
}
}
package com.taidou;
//继承Thread类
public class TestThread2 implements Runnable{
//重写run方法
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("Thread线程"+i);
}
}
//main线程,主线程
public static void main(String[] args) {
//创建Runnable接口的实现类对象
TestThread2 thread2 = new TestThread2();
//创建线程对象,调用start方法启动线程,代理
//Thread thread = new Thread(thread2);
//thread.start();
new Thread(thread2).start();
//main方法体
for (int i = 0; i < 200; i++) {
System.out.println("main线程"+i);
}
}
}
package com.taidou;
//多个线程操作同一对象
//买票
public class TestThread3 implements Runnable{
//票数
private int tickeNums =10;
@Override
public void run() {
buy();
}
//买票的方法
private void buy() {
while (true){
if (tickeNums<=0){
break;
}
//模拟延时
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"买到了倒数第" + tickeNums-- + "张票");
}
}
//main线程,主线程
public static void main(String[] args) {
TestThread3 ticke = new TestThread3();
new Thread(ticke,"小明").start();
new Thread(ticke,"小红").start();
new Thread(ticke,"小刚").start();
}
}
不推荐使用JDK提供的方法停止线程
推荐让线程自己停下来
建议使用一个标志位终止线程运行
boolean flag = true;
public void run() {
while (flag){
//线程方法
}
}
public void stop(){
flag = false;
}
package com.taidou;
//多个线程操作同一对象
//买票
public class TestThread3 implements Runnable{
//票数
private int tickeNums =10;
@Override
public void run() {
buy();
}
//买票的方法
private void buy() {
while (true){
if (tickeNums<=0){
break;
}
//模拟延时
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"买到了倒数第" + tickeNums-- + "张票");
}
}
//main线程,主线程
public static void main(String[] args) {
TestThread3 ticke = new TestThread3();
new Thread(ticke,"小明").start();
new Thread(ticke,"小红").start();
new Thread(ticke,"小刚").start();
}
}
更改加入锁机制,在买票的方法上加入synchronized关键字
只有加入关键字,就能解决线程不安全的问题
package com.taidou;
//多个线程操作同一对象
//买票
public class TestThread4 implements Runnable{
//票数
private int tickeNums =10;
@Override
public void run() {
buy();
}
//买票的方法
private synchronized void buy() {
while (true){
if (tickeNums<=0){
break;
}
//模拟延时
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"买到了倒数第" + tickeNums-- + "张票");
}
}
//main线程,主线程
public static void main(String[] args) {
TestThread4 ticke = new TestThread4();
new Thread(ticke,"小明").start();
new Thread(ticke,"小红").start();
new Thread(ticke,"小刚").start();
}
}
原文:https://www.cnblogs.com/taidou-hth/p/12358187.html