package base;/*** 安全终止线程*/public class StopThreadSafe {private static User u = new User();public static void main(String[] args) throws InterruptedException {new ReadObjectThread().start();while (true) {ChangeObjectThread t = new ChangeObjectThread();t.start();Thread.sleep(150);// stopMe()修改stopme标记t.stopMe();}}public static class User {private int id;private String name;public User() {super();id = 0;name = "0";}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "User[id=" + id + ",name=" + name + "];";}}public static class ChangeObjectThread extends Thread {volatile boolean stopme = false;// 标记线程是否需要退出public void stopMe() {stopme = true;}@Overridepublic void run() {while (true) {// 检查线程是否需要退出if (stopme) {System.out.println("exit by stop me");break;}synchronized (u) {int v = (int) System.currentTimeMillis();u.setId(v);try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}u.setName(String.valueOf(v));}Thread.yield();}}}public static class ReadObjectThread extends Thread {@Overridepublic void run() {while (true) {synchronized (u) {if (u.id != Integer.parseInt(u.name)) {System.out.println(u.toString());}}Thread.yield();}}}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。